How to use setState is modifying nested objects

divStyle:[

        {activeStyle:""},{activeStyle:""},{activeStyle:""},{activeStyle:""},{activeStyle:""},{activeStyle:""},{activeStyle:""},{activeStyle:""},{activeStyle:""}

      ]

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36

Challenge: Build a Drum Machine

Link to the challenge:

If your full object is “the state”, then you must create a new object - it has to be a different reference.

This changes the nested value but it does not change the original object.

let myObj = {
  prop: {
    num: 42,
  },
};

myObj.prop.num = 127;

This will change the original object, it will be a new reference.

let myObj = {
  prop: {
    num: 42,
  },
};

myObj = {
  ...myObj,
  prop: {
    ...myObj.prop,
    num: 127,
  },
};

That is what you want. There are other ways to make a shallow clone, but this is the “ES6 way”. There may be cleaner ways to do this if you don’t need the nested references changed, or if you know for sure what the props are now and forever, like:

myObj = {
  prop: {
    num: 127,
  },
};

React needs a new reference so it knows that the data has changed. If the object reference doesn’t change, then React has no way of knowing. It won’t go and check every single property. It assumes that it’s data is immutable - you don’t change reference variables, you completely replace them with a new version.

It would be nice with some more context. What are you trying to achieve with this code?

I get the feeling it might not be the correct solution to what you are trying to do (just based on the variable/property names).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.