user-email-context.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import { createContext, useContext, useReducer, useCallback } from 'react'
  2. import getMeta from '../../../utils/meta'
  3. import useSafeDispatch from '../../../shared/hooks/use-safe-dispatch'
  4. import { UserEmailData } from '../../../../../types/user-email'
  5. import { normalize, NormalizedObject } from '../../../utils/normalize'
  6. // eslint-disable-next-line no-unused-vars
  7. enum Actions {
  8. SET_LOADING_STATE = 'SET_LOADING_STATE', // eslint-disable-line no-unused-vars
  9. }
  10. type ActionSetLoading = {
  11. type: Actions.SET_LOADING_STATE
  12. payload: boolean
  13. }
  14. type State = {
  15. isLoading: boolean
  16. data: {
  17. byId: NormalizedObject<UserEmailData>
  18. }
  19. }
  20. type Action = ActionSetLoading
  21. const setLoadingAction = (state: State, action: ActionSetLoading) => ({
  22. ...state,
  23. isLoading: action.payload,
  24. })
  25. const initialState: State = {
  26. isLoading: false,
  27. data: {
  28. byId: {},
  29. },
  30. }
  31. const reducer = (state: State, action: Action) => {
  32. switch (action.type) {
  33. case Actions.SET_LOADING_STATE:
  34. return setLoadingAction(state, action)
  35. }
  36. }
  37. const initializer = (initialState: State) => {
  38. const normalized = normalize<UserEmailData>(getMeta('ol-userEmails'), {
  39. idAttribute: 'email',
  40. })
  41. const byId = normalized || {}
  42. return {
  43. ...initialState,
  44. data: {
  45. ...initialState.data,
  46. byId,
  47. },
  48. }
  49. }
  50. function useUserEmails() {
  51. const [state, dispatch] = useReducer(reducer, initialState, initializer)
  52. const safeDispatch = useSafeDispatch(dispatch)
  53. const setLoading = useCallback(
  54. (flag: boolean) => {
  55. safeDispatch({
  56. type: Actions.SET_LOADING_STATE,
  57. payload: flag,
  58. })
  59. },
  60. [safeDispatch]
  61. )
  62. return {
  63. state,
  64. setLoading,
  65. }
  66. }
  67. const UserEmailsContext = createContext<
  68. ReturnType<typeof useUserEmails> | undefined
  69. >(undefined)
  70. UserEmailsContext.displayName = 'UserEmailsContext'
  71. type UserEmailsProviderProps = {
  72. children: React.ReactNode
  73. } & Record<string, unknown>
  74. function UserEmailsProvider(props: UserEmailsProviderProps) {
  75. const value = useUserEmails()
  76. return <UserEmailsContext.Provider value={value} {...props} />
  77. }
  78. const useUserEmailsContext = () => {
  79. const context = useContext(UserEmailsContext)
  80. if (context === undefined) {
  81. throw new Error('useUserEmailsContext must be used in a UserEmailsProvider')
  82. }
  83. return context
  84. }
  85. export { UserEmailsProvider, useUserEmailsContext }