Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object assign and spread operator mutate React state?

I wonder if I did something wrong because as far as I know: Object.assign and spread operator will create new object, therefore we can avoid mutate the internal state with is a bad practice. But in my project those two don't seem to work.

First, in my constructor, I setup the state as below:

this.state = {
  article: {
    title: "",
    alias: "",
    category: "JAVA",
    steps: [
      {
        stepId: 1,
        title: "Dummy title",
        description: "The quick brown fox jump over the lazy dog",
        length: 30
      }
    ]
  },
  description: "",
  newStep: {
    title: "",
    length: 0
  }
}

Later, I add an addStep() function:

addStep() {

  console.log(this.state.article.steps);

  let article = { ...this.state.article };

  article.steps.push({
    stepId: _.last(this.state.article.steps).stepId + 1,
    title: this.state.newStep.title,
    length: this.state.newStep.length,
    description: "",
  });

  console.log(this.state.article.steps);
}

And here the result: enter image description here

As you can see this.state.article.steps has been mutated. The same goes for Object.assign. Finally I decide to use and that solved my problem.

let article = JSON.parse(JSON.stringify(this.state.article));

Result: enter image description here

like image 234
Lê Quang Bảo Avatar asked Dec 24 '22 11:12

Lê Quang Bảo


1 Answers

Object.assign{} and object spread won't deep clone an object.

It will mutate steps.

It is discussed in the following thread:

How do I correctly clone a JavaScript object?

like image 176
kawamurakazushi Avatar answered Jan 11 '23 08:01

kawamurakazushi