Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 452
Thomas Mirmo Avatar asked Apr 07 '17 05:04

Thomas Mirmo


2 Answers

this.setState(prevState => ({
  name: company.word,
  currentCompany: (prevState.currentCompany + 1)
}));
like image 140
Thomas Mirmo Avatar answered Oct 21 '22 04:10

Thomas Mirmo


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.

like image 3
Mayank Shukla Avatar answered Oct 21 '22 05:10

Mayank Shukla