Thomas Mirmo
Thomas Mirmo

Reputation: 181

Set multiple states in setState - React.js ES6

How would I add the name const to the second setState method? In order to increment currentCompany I must include the prevState. When I attempt to add the name const it does not work.

const name = company.word;

this.setState({ name });

this.setState(prevState => ({
  currentCompany: (prevState.currentCompany + 1)
}));

Thank you for your help :)

Upvotes: 6

Views: 29575

Answers (3)

rahul tiwari
rahul tiwari

Reputation: 17

Function onchange set multiple state onChange(field, value){

const next = {

 ...this.state,

[field]: value

 }
this.setState(next)

 }

on HTML use onChange=e)=>this.onChange('title',e.target.value)}

Upvotes: -1

Thomas Mirmo
Thomas Mirmo

Reputation: 181

this.setState(prevState => ({
  name: company.word,
  currentCompany: (prevState.currentCompany + 1)
}));

Upvotes: 11

Mayank Shukla
Mayank Shukla

Reputation: 104369

You can write it like this also:

this.setState({ 
    name ,
    currentCompany: this.state.currentCompany + 1
})

Multiple setState within a function is not a good idea, try to do all the calculation then use setState once after that.

Upvotes: 3

Related Questions