-
-
Save thchia/dd1bc8200fd8cff89cfa6c928983e5c4 to your computer and use it in GitHub Desktop.
// Main | |
function combineReducers(reducerDict) { | |
const _initialState = getInitialState(reducerDict); | |
return function(state = _initialState, action) { | |
return Object.keys(reducerDict).reduce((acc, curr) => { | |
let slice = reducerDict[curr](state[curr], action); | |
return { ...acc, [curr]: slice }; | |
}, state); | |
}; | |
} | |
function useStore(rootReducer, state) { | |
const initialState = state || rootReducer(undefined, { type: undefined }); | |
return useReducer(rootReducer, initialState); | |
} | |
// Usage | |
function reducerA(state, action) { | |
// ... | |
} | |
function reducerB(state, action) { | |
// ... | |
} | |
function reducerC(state, action) { | |
// ... | |
} | |
const rootReducer = { | |
group1: combineReducers({ a: reducerA, b: reducerB }), | |
group2: reducerC | |
} | |
// Use this in a Context Provider and get access to state and dispatch | |
// anywhere by using useContext. | |
const [state, dispatch] = useStore(rootReducer) // optional state object as second arg | |
// Helpers | |
function getInitialState(reducerDict) { | |
return Object.keys(reducerDict).reduce((acc, curr) => { | |
const slice = reducerDict[curr](undefined, { type: undefined }); | |
return { ...acc, [curr]: slice }; | |
}, {}); | |
} |
neat
const rootReducer = {
group1: combineReducers({ a: reducerA, b: reducerB }),
group2: reducerC
}
should be
const rootReducer = combineReducers({
group1: combineReducers({ a: reducerA, b: reducerB }),
group2: reducerC
})
@viotti oops you are right! Anyway I think a lot of this has been superseded by the official hooks implementation in react-redux.
Instead of a useStore
hook however (that has the same signature as useReducer
), the recommended approach is to make use of useDispatch
and useSelector
to access state and the dispatch function separately.
@thchia well, to those who are not using Redux, like me, this is still useful. Thanks.
i cannot see the default values of each reducer on the rootReducer
@juanriglos each reducer should define its default state, not the rootReducer.
Yes i am sure about that, but tried to access a reducer state in the store, before made any action, and second the perfomance it is not the best option, it will bring the hole store always
@thchia I'm new to react-hooks, Can you give example how to use this combineuseReducers?