Redux docs suggest using normalizr
to design the shape of the state like this:
{
entities: {
cards: {
42: {
id: 42,
text: 'Hello',
category: 2
},
43: {
id: 53,
text: 'There?',
category: 1
},
}
categories: {
1: {
id: 1,
name: 'Questions'
}
2: {
id: 2,
name: 'Greetings'
},
}
},
filter: 'SHOW_ALL',
allCardsList: {
isFetching: false,
items: [ 42, 43 ]
},
}
Naturally, this would split into three composable reducers (filter
, allThingsList
and entities
), but it seems to me that I'd want to write separate reducers for entities.cards
and entities.categories
.
Is there a way to split management of entities into subreducers that would allow composition like this:
let rootReducer = combineReducers({
entities: {
things,
categories
},
filter,
allCardsList
});
Are there any advantages to keeping the cards
and categories
in entities
, instead of keeping on the root level (which will allow composition using combineReducers
)?
{
cards: { ... },
categories: { ... },
filter: 'SHOW_ALL',
allCardsList: { ... }
}
Is there a way to split management of entities into subreducers that would allow composition like this?
Sure! combineReducers()
just gives you a reducer so you can use it several times:
let rootReducer = combineReducers({
entities: combineReducers({
things,
categories
}),
filter,
allCardsList
});
The shopping-cart example in Redux repo demonstrates this approach.
Are there any advantages to keeping the cards and categories in entities, instead of keeping on the root level?
It’s up to you but I find the structure you suggest easier to work with. It’s indeed easier for understanding to group all entities under a single key, and it is possible with combineReducers()
as I show above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With