Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 437
ChrisBratherton Avatar asked May 03 '19 14:05

ChrisBratherton


2 Answers

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
);
like image 87
Rémi Avatar answered Nov 03 '22 13:11

Rémi


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
    );
like image 32
timdeschryver Avatar answered Nov 03 '22 13:11

timdeschryver