Source:  Twitter logo

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

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.

80 users liked answer #0dislike answer #080
Florent profile pic
Florent

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

58 users liked answer #1dislike answer #158
Joseph Nields profile pic
Joseph Nields

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)}
  }
}
11 users liked answer #2dislike answer #211
D.W profile pic
D.W

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
  }
}
1 users liked answer #3dislike answer #31
iamandrewluca profile pic
iamandrewluca

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}
}
1 users liked answer #4dislike answer #41
Vinayak V Naik profile pic
Vinayak V Naik

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).