|
| 1 | +import React, { createContext, useContext, useReducer } from "react"; |
| 2 | +import PropTypes from "prop-types"; |
| 3 | + |
| 4 | +export const StateContext = createContext(); |
| 5 | + |
| 6 | +/** |
| 7 | + * Wrap this component around main App content |
| 8 | + * @example |
| 9 | + <StateProvider initialState={initialState} reducer={reducer}> App </StateProvider> |
| 10 | + */ |
| 11 | +export const StateProvider = ({ reducer, initialState, children }) => ( |
| 12 | + <StateContext.Provider value={useReducer(reducer, initialState)}> |
| 13 | + {children} |
| 14 | + </StateContext.Provider> |
| 15 | +); |
| 16 | + |
| 17 | +/** |
| 18 | + * use this Hook inside your any component to access your store |
| 19 | + * @example |
| 20 | + const [{ user }, dispatch] = useStateValue(); |
| 21 | + */ |
| 22 | +export const useStateValue = () => useContext(StateContext); |
| 23 | + |
| 24 | +/** |
| 25 | + * if you have more than one reducer use this function to create root_reducer, we mix all of your reducers into one reducer function |
| 26 | + * @param {object} reducers |
| 27 | + * @example |
| 28 | + const root_reducer = combineReducers({user: reducer_user,items: reducer_items}); |
| 29 | + */ |
| 30 | +export const combineReducers = reducers => { |
| 31 | + // First get an array with all the keys of the reducers (the reducer names) |
| 32 | + const reducerKeys = Object.keys(reducers); |
| 33 | + |
| 34 | + return function combination(state = {}, action) { |
| 35 | + // This is the object we are going to return. |
| 36 | + const nextState = {}; |
| 37 | + |
| 38 | + // Loop through all the reducer keys |
| 39 | + for (let i = 0; i < reducerKeys.length; i++) { |
| 40 | + // Get the current key name |
| 41 | + const key = reducerKeys[i]; |
| 42 | + // Get the current reducer |
| 43 | + const reducer = reducers[key]; |
| 44 | + // Get the the previous state |
| 45 | + const previousStateForKey = state[key]; |
| 46 | + // Get the next state by running the reducer |
| 47 | + const nextStateForKey = reducer(previousStateForKey, action); |
| 48 | + // Update the new state for the current reducer |
| 49 | + nextState[key] = nextStateForKey; |
| 50 | + } |
| 51 | + return nextState; |
| 52 | + }; |
| 53 | +}; |
| 54 | + |
| 55 | +// --- propTypes |
| 56 | +StateProvider.propTypes = { |
| 57 | + /** |
| 58 | + * @return {React.Node} |
| 59 | + */ |
| 60 | + children: PropTypes.node.isRequired, |
| 61 | + |
| 62 | + /** |
| 63 | + * Object containing initial state value. |
| 64 | + */ |
| 65 | + initialState: PropTypes.shape({}).isRequired, |
| 66 | + |
| 67 | + /** |
| 68 | + * |
| 69 | + * @param {object} state |
| 70 | + * @param {object} action |
| 71 | + */ |
| 72 | + reducer: PropTypes.func.isRequired |
| 73 | +}; |
0 commit comments