0

While working with ReactJS setState method to update state I observed that post increment operator was not working(did not get any error as well) so I had to use + 1 instead for the same. Any idea why this behaviour as I am new to React and got shocked to learn this.

Here is my code: This did not work:

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

This worked:

this.setState((prevState) => ({
      left: prevState.left + 1
}));
Peter
  • 10,492
  • 21
  • 82
  • 132

2 Answers2

2

x++ expression first returns the value of x then it increments it

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

should give the expected result

taha
  • 997
  • 9
  • 17
1

This is javascript, you are asigning the prevState to the prevState value :

a = 0; 
a = a++;
a == 0 // true
a++
a == 0 // false
D. Peter
  • 487
  • 3
  • 12