Extension on the combineReducer method as available in Redux libraries
$ npm install --save combine-reducers-enhanced
import {combineReducersEnhanced} from "combine-reducers-enhanced";
const rootReducer = {
ui: {
login: loginReducer,
main: mainReducer
} ,
data: dataReducer
}
const enhancedRootReducer = combineReducersEnhanced(rootReducer);
let store: Store = new Store(enhancedRootReducer);
The description above can be used with older versions of @ngrx/store or standard redux implementations. In that scenario, the enhancedRootReducer will be a function. The newer version of @ngrx/store however expects an ActionReducerMap
. You can get this by passing a flag false as a second parameter to the function like this:
import {combineReducersEnhanced} from "combine-reducers-enhanced";
const rootReducer = {
ui: {
login: loginReducer,
main: mainReducer
} ,
data: dataReducer
}
const enhancedRootReducer: ActionReducerMap = combineReducersEnhanced(rootReducer, false);
Every redux library provides us with a method called combineReducers
(if you don't know this check the documentation. This method is really helpful but has its limitations. This library was created to fix one of this limitations.
During design of your state tree, you typically divide it up into different sections. F.e.
{
ui: uiReducer,
data: dataReducer
}
@ngrx/store provides the combineReducers
method to easily work with such structures.
If you want to work with multiple levels of nesting in your state tree, you need to do something else F.e.
{
ui: {
login:...,
main: ...
} ,
data: ...
}
In that case, you'd could:
- Write a uiReducer yourself which delegates every action related to login to a loginReducer and every 'main' related action to the mainReducer.
- Use a utility such as: https://github.com/brechtbilliet/create-reducer-tree which handles this for you
- Nest the combineReducers method like this:
const rootReducer =
{
ui: combineReducers({
login: loginReducer,
main: mainReducer
}),
data: dataReducer
}
Option 1 provides you with extra work and option 2 forces you to work with a third party library. I personally prefer option 3 where you nest the combineReducers method inside your tree. This could actually be easily integrated into the current combineReducers method and make the following possible:
rootReducer = {
ui: {
login: loginReducer,
main: mainReducer
},
data: dataReducer
}
new Store(rootReducer)
It's a lot cleaner than approach where you nest the combineReducers method yourself. This implemented by making the combineReducers function recursive.
MIT © KwintenP