React Pomodoro clock - props don't update

Hey. I’m building Pomodoro Clock w/ React and I’ve encountered a problem. I’m updating the state of the parent element (App) from child element (BreakCounter) and it updates like a charm, But when I try to pass the updated parent state back to the same child - it doesn’t work. Child prop (this.props.breakCounter) does not update. What can I do to solve this problem? Pomodoro codepen - https://codepen.io/VasV/pen/oNbzmKQ?editors=1111

You are using setState incorrectly.

You have this.setState = ({...stateChanges}) in your methods.

It should be this.setState({...stateChanges}).

The only reason why it looks like it works is that you are mutating the state directly inside your setState calls, which you should not be doing.

// Don't do this
this.setState = ({
  breakCounter: this.state.breakCounter = 5,
});

// Just do this
this.setState({
  breakCounter: 5,
});

This will not work, can you think of why?

breakCounter: state.breakCounter++

breakCounter: ++state.breakCounter
// or
breakCounter: state.breakCounter + 1

If you need the current state in a setState call it may be better to use an updater function. And if you want to log the state after setState you can use the callback function it accepts.

breakCounterIncrement = () => {
  this.setState(
    (state, props) => ({
      breakCounter: state.breakCounter + 1
    }), () => console.log("breakCounterIncrement", this.state)
  );
};
1 Like