1

I want to render numbers from state, but when I click button nothing happens. How could I fix that?

class App extends Component {
        state = {
            hours: 0,
            min: 0,
            sec: 0
        }

handleClick = () => {
    this.setState({
        sec: this.state.sec++
    })
}

render() {
    return (
        <div>
            <main className="time-change">
                <form>
                    <h2>{this.state.hours}:{this.state.min}:{this.state.sec}</h2> 
                </form>
                <button onClick={this.handleClick}>^</button>
            </main>
        </div>
    )
}

}

Wets
  • 180
  • 1
  • 11
  • 8
    `this.state.sec++` mutates state, and returns the value before update (see [Postfix increment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment)). Instead change to `this.state.sec + 1`. – Brian Thompson Jun 23 '20 at 15:31
  • 1
    Along with this, you are also missing a constructor, which should call the super() function in order to properly inherit from the Component parent class. – Joseph Hines Jun 23 '20 at 15:33
  • Agree with @BrianThompson, because `this.state.sec` is a mutates state, if you want to update state you can use `this.state.sec + 1`. thanks! – massam Jun 23 '20 at 15:45

2 Answers2

1

this.state.sec++ mutates the state, and we should never mutate the state directly (https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly).

Also note, the setState is asynchronous, and such a code with a counter update may fail. You may find a good explanation about its asynchronous nature here and in the docs.

With this in mind, it's a good practice to use the form of setState() that accepts a function rather than an object like:

handleClick = () => {
    this.setState(prevState => ({
        sec: prevState.sec + 1
    }));
}
Olga
  • 217
  • 1
  • 8
0

As mentioned in the comments this.state.sec++ will first return the actual value of this.state.sec and then increment it's value. Also if your new state depends on the old state it is recommended to use an updater function in the setState

this.setState((prevState) => {
    sec: prevState.sec + 1
});
ktowen
  • 306
  • 3
  • 8