Package Exports
- flat-combine-reducers
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (flat-combine-reducers) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
flat-combine-reducers
Turns multiple reducer functions, into a single reducer function, with support of declaring the initial states as default parameters.
It will call all the child reducers, and gather their results into a single state object by assign
the result objects together from left to right.
The reason of the name is it flaten the state
of using the combineReducers
in redux.
npm install --save flat-combine-reducers
Why
To prevent the reducer growing too large, Redux provides a function called combineReducers
to let us structure the reducer. However, it will structure not only the reducer itself but also your state. Each state that managed by distinct reducer will be separated into a deep object with a specified key.
Moreover, the combine logic should idealy focus on the combining only when create the store. And each reducers should manage their own states as the default values of the first parameter. However, the combineReducers
require us to give the initial state as one parameter when calling it. Thus, it could make the responsibilities of the code a mess.
Examples
Return identity reducer if parameter is empty
const reducer = flatCombineReducers();
expect(reducer({ A: 1, B: 2 }, "indifferentAction")).to.deep.equal({ A: 1, B: 2 });
expect(reducer({ A: 1, B: 2 })).to.deep.equal({ A: 1, B: 2 });
expect(reducer()).to.deep.equal({});
Combines multiple reducers into one
const reducer = flatCombineReducers(
(prevState, action) => ({A: prevState.A + action.value}),
(prevState, action) => ({B: prevState.B * action.value})
);
expect(reducer({ A: 1, B: 2 }, { value: 3 })).to.deep.equal({ A: 4, B: 6 });
Supports separated initial state values as default parameters
const reducer = flatCombineReducers(
(prevState = { A: 1 }, action) => ({A: prevState.A + action.value}),
(prevState = { B: 2 }, action) => ({B: prevState.B * action.value})
);
expect(reducer(undefined, { value: 3 })).to.deep.equal({ A: 4, B: 6 });
Assigns the states from right to left
const reducer = flatCombineReducers(
(prevState = { A: 1 }, action) => ({...prevState, A: prevState.A + action.value}),
(prevState = { A: 2 }, action) => ({...prevState, A: prevState.A * action.value})
);
expect(reducer(undefined, { value: 3 })).to.deep.equal({ A: 6 });