Created
July 30, 2021 02:40
-
-
Save MeetMartin/b96bb51763280165ce924631dfb216e5 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
// /src/store/StoreContext.js | |
import React, { createContext, useReducer, useEffect } from 'react'; | |
import { reducer, initialState } from './reducers'; | |
import { useActions } from './actions'; | |
import { applyMiddleware } from './middleware'; | |
const StoreContext = createContext(initialState); | |
const StoreProvider = ({ children }) => { | |
// Set up reducer with useReducer and our defined reducer, initialState from reducers.js | |
const [state, dispatch] = useReducer(reducer, initialState); | |
// Attach middleware to capture every dispatch | |
const enhancedDispatch = applyMiddleware(state)(dispatch); | |
// Create an object of all our actions, handling special cases where a simple dispatch is too primitive | |
const actions = useActions(state, enhancedDispatch); | |
// Log new state | |
useEffect( () => { | |
console.debug('[StoreProvider state] state updated', state);; | |
}, [state]); | |
return ( | |
<StoreContext.Provider value={{ state, enhancedDispatch, actions }}> | |
{children} | |
</StoreContext.Provider> | |
); | |
}; | |
export { StoreContext, StoreProvider }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment