Is it possible to combine reducers that are nested with the following structure:
import 'user' from ... import 'organisation' from ... import 'auth' from ... // ... export default combineReducers({ auth: { combineReducers({ user, organisation, }), auth, }, posts, pages, widgets, // .. more state here });
Where the state has the structure:
{ auth: { user: { firstName: 'Foo', lastName: 'bar', } organisation: { name: 'Foo Bar Co.' phone: '1800-123-123', }, token: 123123123, cypher: '256', someKey: 123, } }
Where the auth
reducer has the structure:
{ token: 123123123, cypher: '256', someKey: 123, }
so maybe the spread operator is handy? ...auth
not sure :-(
Having multiple reducers become an issue later when we create the store for our redux. To manage the multiple reducers we have function called combineReducers in the redux. This basically helps to combine multiple reducers into a single unit and use them.
It is perfectly fine to combine your nested reducers using combineReducers .
The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore . The resulting reducer calls every child reducer, and gathers their results into a single state object.
Multiple slice reducers can respond to the same action, independently update their own slice as needed, and the updated slices are combined into the new state object. Because this pattern is so common, Redux provides the combineReducers utility to implement that behavior.
It is perfectly fine to combine your nested reducers using combineReducers
. But there is another pattern which is really handy: nested reducers.
const initialState = { user: null, organisation: null, token: null, cypher: null, someKey: null, } function authReducer(state = initialState, action) { switch (action.type) { case SET_ORGANISATION: return {...state, organisation: organisationReducer(state.organisation, action)} case SET_USER: return {...state, user: userReducer(state.user, action)} case SET_TOKEN: return {...state, token: action.token} default: return state } }
In the above example, the authReducer
can forward the action to organisationReducer
and userReducer
to update some part of its state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With