0

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

Community
  • 1
  • 1
Charlie A
  • 171
  • 1
  • 6

1 Answers1

2

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

Mark Williams
  • 2,268
  • 1
  • 11
  • 14