Charlie A Charlie A - 1 year ago 63
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,
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?


Answer Source

Object.assign doesn't make deep copies. There are several alternatives you could consider, for example the React docs mention There's also object-assign-deep

Good article here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download