Charlie A Charlie A - 1 month ago 4
React JSX Question

Why does cloning JS objects more then 1 level deep break immutability in Redux?

Take the following example of a simple deep nested JS object:

customer: {
email: '',
address: {
addressLines: [''],
postcode: '',
city: ''
}
}


The following update does not trigger a state mutation in reduxImmutableStateInvariant:

let objectToUpdate = {
address: {
addressLines: customer.address.addressLines,
postcode: value,
city: customer.address.city
}
};
customer = Object.assign({}, customer, objectToUpdate);


Where as this update does trigger a state mutation error:

customer.address['postcode'] = value;


And one level deep does not:

customer['email'] = value;


When needing to preform updates to state that are more than 1 level deep the only approach is to use normalizr or immutable-js or to roll your own comprehensive bespoke solution?

Thanks

Answer

Object.assign doesn't make deep copies. There are several alternatives you could consider, for example the React docs mention https://github.com/kolodny/immutability-helper. There's also object-assign-deep

Good article here: https://medium.com/pro-react/a-brief-talk-about-immutability-and-react-s-helpers-70919ab8ae7c#.awnjvns82

Comments