Created
November 20, 2020 22:01
-
-
Save w8r/f314b7222db1495b795153ca2433c326 to your computer and use it in GitHub Desktop.
Create data context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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