sinawic
sinawic

Reputation: 157

unexpected react component state value change

I am trying to update the state value but first I have loaded it in another varand after changes made on the new var it is going to setState and update the original state value. but unexpectedly changes made to the temp var already changes the component state value!

var postData = this.state.postData;
postData.likes = postData.likes + 1;
console.log(postData.likes, this.state.postData.likes);

the console.log values: (1, 1) (2, 2) ...

Upvotes: 0

Views: 241

Answers (3)

Lukáš Gibo Vaic
Lukáš Gibo Vaic

Reputation: 4420

you should never ever mutate state, always use setState, and for copying object user spread notation "..."

this.setState(((prevState) => ({
  postData:{
    ...prevState.postData,
    likes: prevState.postData.likes + 1,

  }
});

Upvotes: 1

Thien
Thien

Reputation: 31

You can also use ES2018 spread notation like var postData = {...this.state.postData}; to clone the object and manipulate it before assigning back to state.

Upvotes: 0

Jayce444
Jayce444

Reputation: 9063

Since postData is an object, don't save it directly in another variable since that will create a reference to the one in the state, not a copy. And if it's a reference, changing one will change the other cos they're both pointing to the same object.

Make a copy of it first"

    var postData = Object.assign({}, this.state.postData)

and then change it. Then when you're done, use setState({postData})

Upvotes: 1

Related Questions