javascriptreactjssetstate

react setState callback doesn't have the updated state


if monthOffset = 12 the condition will evaluate to true and update the yearOffset state to 2017 if yearOffset = 2018. Based on the react docs and other answers I've read, the callback function in this.setState fires after the state has been updated, yet the console.log() is still outputting 2018. I've tried a couple different methods of implementing this code based on answers form other related questions but mine isn't working. I'm not sure why.

handleClick(e) {
  const { monthOffset, yearOffset } = this.state
  this.setState({ monthOffset: monthOffset - 1 })
  if ( monthOffset - 1 === 11 ) { this.setState((prevState) => { 
    return { yearOffset: prevState.yearOffset - 1 } },
    () => {console.log("yearOffset", yearOffset)}
  )}
  console.log("clicked")
}

Solution

  • Perhaps you could simplify your logic in the following way, to avoid multiple calls to setState which may be causing unexpected results:

    handleClick(e) {
    
      const { monthOffset, yearOffset } = this.state
    
      // call setState once
      this.setState({ 
    
        // Always decrement month offset
        monthOffset : monthOffset - 1, 
    
        // Only decrement year offset if current month offset === 12
        yearOffset : (monthOffset === 12) ? yearOffset - 1 : yearOffset
    
      }, () => {
    
        console.log("state updated to", this.state)
      })
    
      console.log("clicked")
    }