Skip to content Skip to sidebar Skip to footer

Reactjs: Call A Timer Function On Button Click

PLEASE NOTE: This is not a duplicate of ReactJS - Need to click twice to set State and run function. The solution there does not work for me. This is my initial state: constructor(

Solution 1:

Use the callback approach for setState,since it takes some time to mutate the state and as JS is async , this.startTime() is executed even before the state has mutated and hence you need the second click which does the same thing but by this time the state is already changed and hence it works

changeGameStatus = (status) => {
    console.log('status = ' + status)
    this.setState({
        game: {
            status: status
        }
    }, () => {
         console.log('new status:' + this.state.game.status)

    this.startTimer()
    })

}

Post a Comment for "Reactjs: Call A Timer Function On Button Click"