this.setState question (React: Render Conditionally from Props)

Can someone explain to me why passing in state (instead of using this.state) was failing here?
I thought that was the more appropriate way to do it because of the possible batch updates of state.

The answer was:

  handleClick() {
    this.setState({
      counter: this.state.counter + 1 // Change this line
    });
  }

while I was trying:

  handleClick() {
    this.setState(state => {
      counter: state.counter + 1 // Change this line
    });
  }

From this exercise:

https://www.freecodecamp.org/learn/front-end-libraries/react/render-conditionally-from-props

You have to add parenthesis after =>, like so:

this.setState(state => ({
  counter: state.counter + 1 // Change this line
}));

So that this function state => ({ ... }) returns an object. Without parenthesis, it’s just a block of code.

I think following code illustrates it pretty well:

this.setState(state => {
  const newState = { counter: state.counter + 1 };
  return newState;
}
3 Likes

Ahh of course. Thanks for the explanation and pointing out my error!