I am working with react reducer and came across one scenario and would like to know the better way to handle. I have array of object list and i would like to modify one of the object from list in reducer. As per the standard we should not mutate the state. I have the following example:
const state =
{
items : [
{
'id': 1,
'name': 'test1',
'price': 10,
'work': {
'work1': 1
}
},
{
'id': 2,
'name': 'test2',
price: 20
},
{
'id': 3,
'name': 'test3',
price: 30
}
]
};
// here I would like to find item with id = 1 and modify that object with price = 40 and add new property into nested work property.
const test = state.items.map(item => {
if (item.id ===1) {
let newItem = {...item};
newItem['price'] = 40;
newItem['work'] = {...newItem['work'], 'work2': 2}
return newItem;
}
return item;
})
I have checked the original state object and the new object after computation and found that state object is not being mutate. I would like to know, is this the right approach to work with array of object list with reducer or is there any other standard way to do this.
I would like to thanks in advance.