Nested redux reducers

AndrewMcLagan picture AndrewMcLagan · Apr 22, 2016 · Viewed 31.8k times · Source

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

Answer

Florent picture Florent · Apr 22, 2016

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.