Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use combineReducers to compose deep state reducers?

Tags:

redux

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: { ... }
}
like image 989
c10b10 Avatar asked Feb 07 '23 08:02

c10b10


1 Answers

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.

like image 78
Dan Abramov Avatar answered May 27 '23 09:05

Dan Abramov