Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested redux reducers

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 :-(

like image 697
AndrewMcLagan Avatar asked Apr 22 '16 06:04

AndrewMcLagan


People also ask

Can Redux have multiple reducers?

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.

Can you nest combineReducers?

It is perfectly fine to combine your nested reducers using combineReducers .

What is combine reducers in Redux?

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.

Can multiple reducers handle same action?

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.


1 Answers

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.

like image 134
Florent Avatar answered Sep 24 '22 14:09

Florent