Provider.tsx 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import React, { createContext, useReducer, Dispatch, FC } from "react";
  2. import reducer, { State, getInitialState } from "./reducer";
  3. import { Action } from "./actionTypes";
  4. const Provider: FC = ({ children }) => {
  5. const [state, dispatch] = useReducer(reducer, getInitialState());
  6. return (
  7. <StateContext.Provider value={state}>
  8. <DispatchContext.Provider value={asyncDispatchWrap(dispatch)}>
  9. {children}
  10. </DispatchContext.Provider>
  11. </StateContext.Provider>
  12. );
  13. };
  14. type AsyncDispatch = (
  15. action: Action | ((...args: any) => Promise<any>)
  16. ) => void;
  17. function asyncDispatchWrap(dispatch: Dispatch<Action>) {
  18. const asyncDispatch: AsyncDispatch = (action) => {
  19. if (action instanceof Function) {
  20. action(dispatch);
  21. return;
  22. }
  23. dispatch(action);
  24. };
  25. return asyncDispatch;
  26. }
  27. export const StateContext = createContext<State>({});
  28. export const DispatchContext = createContext<
  29. (action: Action | ((...args: any) => Promise<any>)) => void
  30. >(asyncDispatchWrap((dispatch) => {}));
  31. export default Provider;