import React, { createContext, useReducer, Dispatch, FC } from "react";
import reducer, { State, getInitialState } from "./reducer";
import { Action } from "./actionTypes";
const Provider: FC = ({ children }) => {
const [state, dispatch] = useReducer(reducer, getInitialState());
return (
{children}
);
};
type AsyncDispatch = (
action: Action | ((...args: any) => Promise)
) => void;
function asyncDispatchWrap(dispatch: Dispatch) {
const asyncDispatch: AsyncDispatch = (action) => {
if (action instanceof Function) {
action(dispatch);
return;
}
dispatch(action);
};
return asyncDispatch;
}
export const StateContext = createContext({});
export const DispatchContext = createContext<
(action: Action | ((...args: any) => Promise)) => void
>(asyncDispatchWrap((dispatch) => {}));
export default Provider;