0

So i have this in my reducer:

export interface PersonState {
  person: Person;
}

which has an array of relatives inside and i'm trying to update it with this:

mutableOn(PersonActions.addRelatives, (state, { relatives }) => {
    const person = state.person;
    person.relatives = relatives;
})

but it gave me an error:

Cannot assign to read only property 'Relatives' of object '[object Object]'

I'm very new with NgRx and Immer so i don't know what i'm doing wrong. Any clue?

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102

1 Answers1

1

you are trying to modify the immutable person, which is forbiden. the correct way of updating your person would be

mutableOn(PersonActions.addRelatives, (state, { relatives }) => {
     return {
       ...state,
       person: {
         ...state.person,
         relatives,
       }
     };
})
Andrei
  • 10,117
  • 13
  • 21
  • 1
    Hi, thanks for the answer. I will try that but i was just following the docs of ngrx-etc, which has the following example: mutableOn(update, (state, { id, newName }) => { const entity = state.entities[id] if (entity) { entity.name = newName } }), and it's says: With the mutableOn function we are able to directly perform state mutations in reducers with less noise, and more concise code. – MeLevantoSinAlarma Sep 29 '20 at 22:18