subscription-dashboard-context.tsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { createContext, ReactNode, useContext, useMemo, useState } from 'react'
  2. type SubscriptionDashboardContextValue = {
  3. recurlyLoadError: boolean
  4. setRecurlyLoadError: React.Dispatch<React.SetStateAction<boolean>>
  5. showCancellation: boolean
  6. setShowCancellation: React.Dispatch<React.SetStateAction<boolean>>
  7. showChangePersonalPlan: boolean
  8. setShowChangePersonalPlan: React.Dispatch<React.SetStateAction<boolean>>
  9. }
  10. export const SubscriptionDashboardContext = createContext<
  11. SubscriptionDashboardContextValue | undefined
  12. >(undefined)
  13. export function SubscriptionDashboardProvider({
  14. children,
  15. }: {
  16. children: ReactNode
  17. }) {
  18. const [recurlyLoadError, setRecurlyLoadError] = useState(false)
  19. const [showCancellation, setShowCancellation] = useState(false)
  20. const [showChangePersonalPlan, setShowChangePersonalPlan] = useState(false)
  21. const value = useMemo<SubscriptionDashboardContextValue>(
  22. () => ({
  23. recurlyLoadError,
  24. setRecurlyLoadError,
  25. showCancellation,
  26. setShowCancellation,
  27. showChangePersonalPlan,
  28. setShowChangePersonalPlan,
  29. }),
  30. [
  31. recurlyLoadError,
  32. setRecurlyLoadError,
  33. showCancellation,
  34. setShowCancellation,
  35. showChangePersonalPlan,
  36. setShowChangePersonalPlan,
  37. ]
  38. )
  39. return (
  40. <SubscriptionDashboardContext.Provider value={value}>
  41. {children}
  42. </SubscriptionDashboardContext.Provider>
  43. )
  44. }
  45. export function useSubscriptionDashboardContext() {
  46. const context = useContext(SubscriptionDashboardContext)
  47. if (!context) {
  48. throw new Error(
  49. 'SubscriptionDashboardContext is only available inside SubscriptionDashboardProvider'
  50. )
  51. }
  52. return context
  53. }