2

I have an App component that has a state containing a property "faces" , which is initialised after an object

const initFaces = { left : [[0,0,0],[0,0,0],[0,0,0]], front : [[1,1,1],[1,1,1],[1,1,1]], right : [[2,2,2],[2,2,2],[2,2,2]], back : [[3,3,3],[3,3,3],[3,3,3]], up : [[4,4,4],[4,4,4],[4,4,4]], down : [[5,5,5],[5,5,5],[5,5,5]] }; class App extends React.component{ ... this.state = { faces : initFaces } ... } 

now my app is constantly changing the state of the "faces" property so i tried implementing a button to revert it back to the original state . This is what i have :

this.setState({ faces : initFaces }) 

But this doesnt work , and this does :

this.setState({ faces : { left : [[0,0,0],[0,0,0],[0,0,0]], front : [[1,1,1],[1,1,1],[1,1,1]], right : [[2,2,2],[2,2,2],[2,2,2]], back : [[3,3,3],[3,3,3],[3,3,3]], up : [[4,4,4],[4,4,4],[4,4,4]], down : [[5,5,5],[5,5,5],[5,5,5]] } }) 

Why does it not work simply by referencing the object that has the identical content that i just copied inside of it ?

1

1 Answer 1

3

The issue happens because you are passing the reference to initFaces when initializing your state, so whenever faces changes (assuming you are somehow mutating this.state.faces directly, which is not advised), you are actually changing the same object referenced by initFaces.

You can fix your issue by performing a shallow copy of initFaces when setting the state (and for this, you can use the spread syntax):

class App extends React.component{ ... this.state = { faces : { ...initFaces } } ... } 

And also in your button's implementation to revert the changes:

this.setState({ faces : { ...initFaces } }) 

But if you are indeed directly mutating the state, consider refactoring your code to only change the state by means of setState.

Sign up to request clarification or add additional context in comments.

5 Comments

This answer is wrong... How it has to do with the same object reference? Here you got an example: codesandbox.io/s/zen-maxwell-s5k2k
The OP didn't provide a producible example, I'm pretty sure he just doesn't reset the state right.
OP probably is mutating the state directly, like in here: codesandbox.io/s/late-dream-ygf9c. But, if that's the case, this is not advised (hence the eslint warning). But, as you can see, the problem is reproducible. A more proper solution could be the usage of setState instead of direct mutation.
Mutating the state doesn't trigger render, and he clearly stated "my app is constantly changing the state"
We need to hear from OP for more details, but I believe he's mutating the state in such a way initFaces is also being modified.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.