Last active
          August 11, 2020 22:12 
        
      - 
      
- 
        Save hyukhur/27447633be1b9b6444a7c531a260c039 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
    
  
  
    
  | const { state, dispatch, actionTypes } = SavedState.useStateValue(); | |
| { | |
| AsyncCall.then((result) => { | |
| dispatch({ type: actionTypes.reset, payload: result }); | |
| }) | |
| } | 
  
    
      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 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 }; | |
| }; | 
  
    
      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 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