Benezir
Benezir

Reputation: 113

NGRX state update

this is my State:-

roles =[ {
roleId:"8e8be141-130d-4e5c-82d2-0a642d4b73e1"
name:"HR"
description:"HR of the Company"
isModerator:"N"
},
{
roleId:"8e8be141-130d-4e5c-82d2-0a642d4b73e1"
name:"MR"
description:"MR of the Company"
isModerator:"Y"
}]

this is My reducer:-

on(updateRoleItem, (s, { roleId, item }) => {
        let modifiedState = [...s];
        modifiedState.map((data) => {
            if (data.roleId === roleId) {
                data.name = item;
            }
        })
        return modifiedState;
    })
);

this is what error I am getting:- enter image description here

I want to update the name property of role in array of roles. So I am finding the object by roleId and then updating the name but I am getting error. Can Someone help me with the right way of doing it?

Upvotes: 1

Views: 4016

Answers (1)

timdeschryver
timdeschryver

Reputation: 15505

By default the NgRx state (and actions) are immutable. Which means you can't simply update the properties, but you must create a clone first. To do this, you can use the rest spread syntax. You could also use ngrx-immer.

on(updateRoleItem, (s, { roleId, item }) => {
        return s.map(data => {
          if (data.roleId === roleId) {
                return {...data, name: item };
          }
          return data;
        });
    })
);

with ngrx-immer

immerOn(updateRoleItem, (s, { roleId, item }) => {
    
        s.map((data) => {
            if (data.roleId === roleId) {
                data.name = item;
            }
        })
    })
);

Upvotes: 1

Related Questions