How to update state objects in render when using immer

331 Views Asked by At

If have an array of objects in state:

state = {
    people = []
};

and at some point I update it in some way using immer:

updatePeople = () => {
    this.setState(produce(draft => {
       draft.people.forEach(p => p.age = 30);
    }));
};

and in my render I need to make a change for display purposes:

render = () => {
    const people = [...this.state.people];
    people.forEach(p => p.age += 2);

   return <DataTable data={people} />
}

Then I will hit the following error

Cannot assign to read only property 'age' of object '#<Object>'

This is happening because immer is sealing the objects in the array when making the update. I can clone each item to get a writable copy as a workaround:

const people = this.state.people.map(p => {...p});

however that could get messy with complex objects. Alternatively I could turn the freezing off completely but that feels like bad design.

setAutoFreeze(false)

What is the best way to handle this situation?

0

There are 0 best solutions below