Last active
March 3, 2022 05:24
-
-
Save sakilahmmad71/df0426f2db0d0fc37916c0593ed86940 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { createContext, useContext, useReducer } from 'react'; | |
const MyContext = createContext(); | |
myContext.displayName = 'MyContext'; | |
const MyContextProvider = ({ initialState = {}, ...props }) => { | |
const [state, dispatch] = useReducer( | |
(state, action) => { | |
switch (action?.type) { | |
case 'MYTYPE' : { | |
return {...state, name : action?.payload } | |
} | |
default : { | |
throw new Error(`Unhandled action type: ${action.type}`) | |
} | |
} | |
}, | |
{ initialState } | |
); | |
const value = [state, dispatch]; | |
return <MyContext.Provider value={value} {...props} /> | |
} | |
const useMyContext = () => { | |
const context = useContext(MyContext); | |
if (context === undefined) { | |
throw new Error(`useMyContext must be used within a MyContextProvider`) | |
} | |
return context; | |
} | |
const myAction = dispatch => dispatch({ type : "MYTYPE" }); | |
const myAnotherAction = (dispatch, payload) => dispatch({ type : "MYANOTHERTYPE", data: payload }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment