7

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?

pjpscriv
  • 866
  • 11
  • 20
ChrisBratherton
  • 1,540
  • 6
  • 26
  • 63

2 Answers2

14

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
);
pjpscriv
  • 866
  • 11
  • 20
Rémi
  • 889
  • 1
  • 8
  • 12
  • May i know How to update Optional Properties In NGrx/Eentity – Raja Reddy Jan 22 '21 at 06:54
  • You could do it like that: adapter.updateOne( { id: 2, changes: {...state.entities[2], likes: value} }, { ...state, property1: value, property2: value } ); – Rémi Jan 22 '21 at 20:15
9

You can make the changes manually as @Remi mention, or you can use the map method:

 const newState = adapter.map(
      book =>
        book.title === TheGreatGatsby.title
          ? { ...book, name: 'foo' }
          : book
      state
    );
pjpscriv
  • 866
  • 11
  • 20
timdeschryver
  • 14,415
  • 1
  • 19
  • 32