Skip to content

Instantly share code, notes, and snippets.

@hyukhur
Last active August 11, 2020 22:12
Show Gist options
  • Save hyukhur/27447633be1b9b6444a7c531a260c039 to your computer and use it in GitHub Desktop.
Save hyukhur/27447633be1b9b6444a7c531a260c039 to your computer and use it in GitHub Desktop.
const { state, dispatch, actionTypes } = SavedState.useStateValue();
{
AsyncCall.then((result) => {
dispatch({ type: actionTypes.reset, payload: result });
})
}
import React, { createContext, useContext, useReducer } from "react";
export default (reducer, actionTypes, initialState = {}) => {
const StateContext = createContext([{}, () => {}]);
const StateProvider = ({ children }) => {
const reduced = useReducer(
(state, action) => reducer(state, action, actionTypes),
initialState
);
return (
<StateContext.Provider value={reduced}>{children}</StateContext.Provider>
);
};
const useStateValue = () => {
const [state, dispatch] = useContext(StateContext);
return { state, dispatch, actionTypes };
};
return { useStateValue, StateProvider };
};
export const SavedState = ReactState(
(state, action, actionTypes) => {
switch (action.type) {
case actionTypes.reset:
return {
...action.payload,
};
case actionTypes.update:
return {
...state,
...action.payload,
};
default:
return state;
}
},
{
reset: "reset",
update: "update",
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment