Kyle
Kyle

Reputation: 3

React: setState - which is more correct?

I have a react class component that has a state object and I want to update the object with setState. I can get the state to update correctly two different ways and would like to know if one is more correct than the other.

this.state = {
  people: {
    name: "",
    typeofComponent: "class",
  }
};

onChange = e => {

  // option 1
  this.setState((prevState) => ({
    people: {
        ...prevState.people, name: e.target.value 
    }
  }));

  // option 2
  this.setState({ people: { name: e.target.value }});
}

Upvotes: 0

Views: 1075

Answers (1)

cmgchess
cmgchess

Reputation: 10247

Your second option would work if the state has only 1 field (name in your case). If you set that way it will overwrite the whole people. That's why we need to use spread operator inorder to make sure the other states are not lost

let a = {
  people: {
    name: "",
    typeofComponent: "class",
  }
}

let newName = 'newname'

let withSpread= {people:{...a.people,name:newName}}

let withoutSpread = {people:{name:newName}}

console.log(withSpread)
console.log(withoutSpread)

Upvotes: 1

Related Questions