Last active
December 1, 2018 20:11
-
-
Save Jahans3/b7d848204dd1a624f94e99581ce7e3c9 to your computer and use it in GitHub Desktop.
Use state provider
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
export function useStateProvider ({ initialState, reducers, middleware = [] }) { | |
const [state, _dispatch] = useReducer((state, action) => { | |
return reducers.reduce((state, reducer) => reducer(state, action) || state, state); | |
}, initialState); | |
function dispatch (action) { | |
if (typeof action === 'function') { | |
return action(dispatch, state); | |
} | |
const continueUpdate = middleware.reduce((result, middleware) => { | |
return result !== null ? middleware(action, state) : result; | |
}, undefined); | |
if (continueUpdate !== null) { | |
_dispatch(action); | |
} | |
} | |
return { state, dispatch }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment