React - Write a Simple Counter

Tell us what’s happening:

Describe your issue in detail here.

when updating the state of my component via setState I initially updated count but the state doesn’t change nor will the test pass, yet when I changed it to the name of the eventhandler that is calling setState the code works and the test pass. This doesn’t make sense to me.

Your code so far

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
    // Change code below this line
    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
    this.reset = this.reset.bind(this);
    // Change code above this line
  }
  // Change code below this line
  increment() {
    this.setState((state) => ({
      increment: state.count++
    }))
  }

  decrement() {
    this.setState((state) => ({
      decrement: state.count--
    }))
  }

  reset() {
    this.setState((state) => ({
      count: 0
    }))
  }
  // Change code above this line
  render() {
    return (
      <div>
        <button className='inc' onClick={this.increment}>Increment!</button>
        <button className='dec' onClick={this.decrement}>Decrement!</button>
        <button className='reset' onClick={this.reset}>Reset</button>
        <h1>Current Count: {this.state.count}</h1>
      </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36

Challenge Information:

React - Write a Simple Counter

Welcome to the forum!

I think the confusion here is syntactical. Think about what this does:

state.count++;

On its own, this adds 1 to state.count. But such syntax behaves unexpectedly sometimes:

state.count = 3;
console.log(state.count++); // What does this log?

The way that JS handles this is it first logs state.count to the console, and then increments it. You can try this yourself in some JS scratchpad, like Codepen:

x = 5;
console.log(x++); // 5 (!)
console.log(x); // 6

So, in your increment function, for example, what I think is happening is that the value of state.count is first put into a new variable in state that you’ve called increment, and then state.count is actually incremented. (Maybe you could console.log the value of state.count to convince yourself. Or maybe add something to the returned div that displays state.increment.)

To get around this, the easiest way is to avoid using ++. Think about this example:

x = 5;
console.log(x++); // 5
y = 5;
console.log(y + 1); // 6 (!)

So, instead of using something like count: state.count++;, you could use count: state.count + 1;. That way you don’t have to make unnecessary variables like increment or decrement in state.

Hopefully that makes sense and also addresses your confusion?

1 Like