How can I update a field in an array by reducer? I tried this:
const customers = state.filteredCustomers;
for (const customer of customers) {
for (const addr of customer.addresses) {
addr.selected = false;
}
}
return {
...state,
filteredCustomers: customers,
};
But it throws an error:
TypeError: Cannot assign to read only property 'selected' of object '[object Object]'
What is the best way to do this?
You will have to take a copy of each level of the state. It's here where it can become awkward to update nested state for x levels deep. That's why I would encourage normalizing your state.
Basically, you will have to loop over the customers and copy the properties, next you will have to do the same for the adresses and set selected to false.
return {
...state,
filteredCustomers: state.filteredCustomers.map(c => ({
...c,
addresses: c.adresses.map(a => ({...a, selected: false})
})
};
A second option would be to use immer, Clean NgRx reducers using Immer
There's a library that does this for the createReducer
function in NgRx 8 - https://github.com/timdeschryver/ngrx-etc/#mutableon. Via this approach you use the code snippet posted in the question.