Nested redux reducers

JavascriptReactjsArchitectureReact NativeRedux

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Just wanted to elaborate a bit on the very good answer @Florent gave and point out that you can also structure your app a bit differently to achieve nested reducers, by having your root reducer be combined from reducers that are also combined reducers

For example

// src/reducers/index.js
import { combineReducers } from "redux";
import auth from "./auth";
import posts from "./posts";
import pages from "./pages";
import widgets from "./widgets";

export default combineReducers({
  auth,
  posts,
  pages,
  widgets
});

// src/reducers/auth/index.js
// note src/reducers/auth is instead a directory 
import { combineReducers } from "redux";
import organization from "./organization";
import user from "./user";
import security from "./security"; 

export default combineReducers({
  user,
  organization,
  security
});

this assumes a bit different of a state structure. Instead, like so:

{
    auth: {
        user: {
            firstName: 'Foo',
            lastName: 'bar',
        }
        organisation: {
            name: 'Foo Bar Co.'
            phone: '1800-123-123',
        },
        security: {
            token: 123123123,
            cypher: '256',
            someKey: 123
        }
    },
    ...
}

@Florent's approach would likely be better if you're unable to change the state structure, however

Solution 3 - Javascript

Inspired by @florent's answer, I found that you could also try this. Not necessarily better than his answer, but i think it's a bit more elegant.

function userReducer(state={}, action) {
    switch (action.type) {
    case SET_USERNAME:
      state.name = action.name;
      return state;
    default:
      return state;
  }
} 

function authReducer(state = {
  token: null,
  cypher: null,
  someKey: null,
}, action) {
  switch (action.type) {
    case SET_TOKEN:
      return {...state, token: action.token}
    default:
      // note: since state doesn't have "user",
      // so it will return undefined when you access it.
      // this will allow you to use default value from actually reducer.
      return {...state, user: userReducer(state.user, action)}
  }
}

Solution 4 - Javascript

Example (see attachNestedReducers bellow)

import { attachNestedReducers } from './utils'
import { profileReducer } from './profile.reducer'
const initialState = { some: 'state' }

const userReducerFn = (state = initialState, action) => {
  switch (action.type) {
    default:
      return state
  }
}

export const userReducer = attachNestedReducers(userReducerFn, {
  profile: profileReducer,
})

State object

{
    some: 'state',
    profile: { /* ... */ }
}

Here is the function

export function attachNestedReducers(original, reducers) {
  const nestedReducerKeys = Object.keys(reducers)
  return function combination(state, action) {
    const nextState = original(state, action)
    let hasChanged = false
    const nestedState = {}
    for (let i = 0; i < nestedReducerKeys.length; i++) {
      const key = nestedReducerKeys[i]
      const reducer = reducers[key]
      const previousStateForKey = nextState[key]
      const nextStateForKey = reducer(previousStateForKey, action)
      nestedState[key] = nextStateForKey
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey
    }
    return hasChanged ? Object.assign({}, nextState, nestedState) : nextState
  }
}

Solution 5 - Javascript

Nested Reducers Example:

import {combineReducers} from 'redux';

export default combineReducers({
    [PATH_USER_STATE]: UserReducer,
    [PATH_CART_STATE]: combineReducers({
        [TOGGLE_CART_DROPDOWN_STATE]: CartDropdownVisibilityReducer,
        [CART_ITEMS_STATE]: CartItemsUpdateReducer
    })
});

Output:

{
cart: {toggleCartDropdown: {}, cartItems: {}}
user: {currentUser: null}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewMcLaganView Question on Stackoverflow
Solution 1 - JavascriptFlorentView Answer on Stackoverflow
Solution 2 - JavascriptJoseph NieldsView Answer on Stackoverflow
Solution 3 - JavascriptD.WView Answer on Stackoverflow
Solution 4 - JavascriptiamandrewlucaView Answer on Stackoverflow
Solution 5 - JavascriptVinayak V NaikView Answer on Stackoverflow