Consider the following:
[SELECT]: (state, action) => {
let newState = {...state, newState}
delete newState[action.payload.key]
return(newState)
}
Why is it acceptable for me to mutate the shallow copy, return it and still satisfy the rule about not mutating my state?
It is acceptable because (at least in your example code), the mutation is on the shallow object, so you are not modifying an object that any other code is currently referring to.
It would not be acceptable to make a shallow copy and then modify a nested object! The key is that you clone any and all objects in the object tree that are on the path to the deep property you wish to change.
From the Redux FAQ:
It’s important to remember that whenever you update a nested value, you must also return new copies of anything above it in your state tree. If you have state.a.b.c.d, and you want to make an update to d, you would also need to return new copies of c, b, a, and state. This state tree mutation diagram demonstrates how a change deep in a tree requires changes all the way up.
A reducer in Redux should be pure, which means it must guarantee that it doesn't change or effect anything outside of it's own function (i.e. produces no side effects). If you mutate the passed state object directly, you violate this.
By creating a new copy, you know for certain that no other part of your application uses it (it was just created, so how could they?). Which in turn means that it's safe to mutate it without worrying about strange side effects.
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