Skip to content

Instantly share code, notes, and snippets.

@w8r
Created November 20, 2020 22:01
Show Gist options
  • Save w8r/f314b7222db1495b795153ca2433c326 to your computer and use it in GitHub Desktop.
Save w8r/f314b7222db1495b795153ca2433c326 to your computer and use it in GitHub Desktop.
Create data context
import React, { useReducer, Reducer, createContext, ReactNode, Dispatch } from "react";
type Action = <A>(dispatch: Dispatch<A>) => Function;
export default function <S, A extends Action>(
reducer: Reducer<S, A>,
actions: Record<string, A>,
initialState: S
) {
const Context = createContext<S>({} as S);
const Provider = ({ children }: { children: ReactNode }) => {
const [state, dispatch] = useReducer(reducer, initialState);
const boundActions: Record<string, Function> = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
}
return (
<Context.Provider value={{ state, ...boundActions } as unknown as S}>
{children}
</Context.Provider>
);
};
return { Context, Provider };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment