Redux ~ Combine Reducers - rohit120582sharma/Documentation GitHub Wiki

The most common state shape for a Redux app is a plain Javascript object containing "slices" of domain-specific data at each top-level key.

Similarly, the most common approach to writing reducer logic for that state shape is to have "slice reducer" functions, each with the same (state, action) signature, and each responsible for managing all updates to that specific slice of state.

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 behaviour. It takes an object full of slice reducer functions, and returns a new reducer function.

It can be used at all levels of your reducer structure, not just to create the root reducer. It's very common to have multiple combined reducers in various places, which are composed together to create the root reducer.

It does not handle some use cases, such as

  • A state tree made up of Immutable.js Maps
  • Trying to pass other portions of the state tree as an additional argument to a slice reducer
  • Performing "ordering" of slice reducer calls


Using slice reducers with Immutable.js objects

Since combineReducers currently only works with plain Javascript objects, an application that uses an Immutable.js Map object for the top of its state tree could not use combineReducers to manage that Map.

References


Problem

When createStore is invoked with initialState that is an instance of Immutable.Collection further invocation of reducer will produce an error:

The initialState argument passed to createStore has unexpected type of "Object". Expected argument to be an object with the following keys: "data"

This is because Redux combineReducers treats state object as a plain JavaScript object.

The combineReducers created using redux-immutable uses Immutable.js API to iterate the state.


Solution

redux-immutable package provides its own implementation of combineReducers that knows how to iterate over an Immutable Map instead of a plain Javascript object.

When Redux createStore reducer is created using redux-immutable then initialState must be an instance of Immutable.Collection.

import {
	combineReducers
} from 'redux-immutable';

import {
	createStore
} from 'redux';

const initialState = Immutable.Map();
const rootReducer = combineReducers({});
const store = createStore(rootReducer, initialState);

⚠️ **GitHub.com Fallback** ⚠️