I have a ngrx store with array of objects. What I am looking for is, update(modify) the object inside the array using the array index. My ngrx data will look like,
policies: {
beneficiaries: {
beneficiaries: [{
name: 'pqr'
age: 56
},
{
name: 'xyz'
age: 76
}
]
}
}
I have to update the beneficiary name based on the array index. So I have implemented the following reducer function
on(policiesActions.updateBeneficiaryPercentage, (state, action) => {
return {
...state,
beneficiaries: {
...state.beneficiaries,
beneficiaries: {
...state.beneficiaries.beneficiaries,
[action.index]: {
...state.beneficiaries.beneficiaries[action.index],
name: action.value
}
}
}
};
})
The issue with the above code is that after running this code the structure of my store is changing to
policies: {
beneficiaries: {
beneficiaries: {
0: {
name: 'pqr'
age: 1000
},
1: {
name: 'xyz'
age: 76
}
}
}
}
Please help me to fix the code so that I can update the value without altering the store structure.
Use the Array.map
method:
arr.map((value, index) => index === action.index ? {...value, name: action.value} : value)
Or just use ngrx-etc, which lets you mutate your state in a mutable way while remaining immutable
mutableOn(onAction, (state, action) => {
state.arr[action.index].name = action.name
return state
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With