0

I was playing around in React Native and came across this error. I don't understand why the first snippet throws an error, while the second one runs fine.

This does not work:

let newContent = { ...oldContent }; // <-- oldContent is a 'const'
newContent.value = newValue; // <-- property at 'root level' can be modified
newContent.nested.a = b; // <-- throws 'You attempted to set the key with the value on an object that is meant to be immutable and has been frozen.' 

But this works fine:

let newContent = { ...oldContent };
newContent.value = newValue;
newContent.nested = {
   a: b,
}

The value of nested.a is defined on oldContent.

Is this expected behaviour or am I doing something wrong in the first snippet?

Kipnoedels
  • 1,118
  • 7
  • 22
  • 1
    Cloning doesn't clone nested objects but instead returns references. – pilchard Dec 26 '20 at 21:50
  • Interesting (linked stackoverflow). I am quite suprised that javascript doesn't offer a simple and clean solution for cloning nested objects. – Kipnoedels Dec 26 '20 at 21:56

0 Answers0