Mister_L
Mister_L

Reputation: 2611

ngrx entities adapter addAll and nested state

I have a scenario where I have a list of users on a users page. Each user has his own list of apps, and when a user is clicked, the corresponding list of apps is displayed. I would like to use the ngrx entity adapter, but first I need to design my state. One option is this:

const state = {
   usersState: {
      entities: {},
      apps: {
         entities: {}
      }
   }
}

And the other is this:

const state = {
   usersState: {
      entities: {},
   },
   appsState: {
      entities: {}
   }
}

Since there are no apps outside the users page, the first option makes more sense to me, but with that approach I have a problem: how do I use the addAll method of the adapter? As far as I understand, and correct me if I'm wrong, addAll accepts a payload that represents a list of items as first parameter, the state as second parameter and somehow merges them together. Can you show an example how to use the adapter to update the nested state? Or maybe the solution is to go for the second option? Thanks.

Upvotes: 1

Views: 1268

Answers (1)

timdeschryver
timdeschryver

Reputation: 15525

An adapter is only responsible for one entity, with that being said I think it's possible to do manage child state. For this to work you should create two adapters, it would look like something like this:

return {
  ...state,
  apps: {
    entities: appAdapter.addAll(payload.apps, state.apps)
  }
}

Side note, you should try to keep your state normalized.

Upvotes: 1

Related Questions