I have an array of objects in state:
this.state = {
items: [
{id: 1, someattr: "a string", anotherattr: ""},
{id: 2, someattr: "another string", anotherattr: ""},
{id: 3, someattr: "a string", anotherattr: ""},
]
}
I need to be able to search the items array based on the id property and then update the objects attributes.
I can get the object by filtering or finding on the array using the id param.
What I'm having trouble with is then updating the array and then subsequently updating state without mutation.
//make sure we're not mutating state directly by using object assign
const items = Object.assign({}, this.state.items);
const match = items.find((item) => item.id === id);
At this point I have a matching object and can update it's properties using object spread:
const matchUpdated = { ...match, someattr: 'a new value'};
My question is how do i then update the state with matchUpdated so that it overwrites the object returned by the initial find operation?
this.state = { items: { 1: { someattr: ... }, 2: { ... }, ... } };?this.state.items[id] = { ...this.state.items[id], someattr: 'a new value' }.