Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use state provider
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
You can’t perform that action at this time.