Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. function initRedux(reducer, initialState) {
  2. const StateContext = React.createContext(null)
  3. const DispatchContext = React.createContext(null)
  4.  
  5. function Provider(props) {
  6. const [appState, dispatch] = React.useReducer(reducer, initialState)
  7. return (
  8. <StateContext.Provider value={appState}>
  9. <DispatchContext.Provider value={dispatch}>
  10. {props.children}
  11. </DispatchContext.Provider>
  12. </StateContext.Provider>
  13. )
  14. }
  15.  
  16. function useRedux(extractState, actionMap) {
  17. const appState = React.useContext(StateContext)
  18. const dispatch = React.useContext(DispatchContext)
  19.  
  20. const stateExtract = extractState(appState)
  21.  
  22. const actions = Object.keys(actionMap).reduce((acc, key) => {
  23. const actionCreator = actionMap[key]
  24. const fn = (...args) => {
  25. const action = actionCreator(...args)
  26. if (typeof action === 'function') {
  27. action(dispatch, () => appState)
  28. } else {
  29. dispatch(action)
  30. }
  31. }
  32. return { ...acc, [key]: fn }
  33. }, {})
  34.  
  35. return [stateExtract, actions]
  36. }
  37.  
  38. return { Provider, useRedux }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement