Search code examples
angularngrxngrx-storengrx-entity

Using @ngrx/entity, how can I update an items array


I am using @ngrx/entity and this creates a state that looks like the following:

{
   ids: [1, 2, 3],
   entities: [
     1: {id:1, title: "Some title", likes: {count: 1}},
     2: {id:2, title: "Some title", likes: {count: 1}},
     3: {id:3, title: "Some title", likes: {count: 1}}
   ]
}

@ngrx/entity does give us some cool helpers for updating an item, but it seems (from what I can see in the docs) limited to updating the WHOLE entity only.

However, when a user toggles a 'Like' button, I would like in my reducer to update only that state.entities[2].likes property with the response.

Any ideas on how I can go about this?


Solution

  • As your state is immutable. You need to update the all entity. @ngrx/entity comes with some helpers that you can use to update 1 entity. In your case, you need to use the updateOne method. https://ngrx.io/guide/entity/adapter

    It will look like something like that:

    adapter.updateOne(
    {
      id: 2,
      changes: {...state.entities[2], likes: value}
    },
    state
    );