Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait after setting the state in react

React 16.8 (Using classes not hooks)

consider the following if statement in a function thats called onClick

 if (this.state.opponentIsDead) {
    this.setState({
      disableAttack: 'disabled',
    }, () => {
      this.timer = setTimeout(() => {
        this.props.postFightData({
          train_exp: 100,
          drop_chance: this.state.monster.drop_chance,
          gold_rush_chance: this.state.monster.gold_rush_chance,
          gold_drop: this.state.monster.gold_drop,
        });
      }, 1000);
    });
  }

What I am trying to do is wait a second before posting the fight data if you have won the fight, the time out piece works. But as you can see I am updating the state to disable the button.

What I was thinking of doing is moving the timeout to the componentDidUpdate method, that way the component will re-render and the button will be disabled, how ever I feel thats the wrong way to do it.

I understand you can wrap the setState in an async function, but I also wonder if thats the best approach.

The goal is to disable the button, then wait 1 second and post the data. Whats the best approach?

Whats wrong with this approach?

For those who might not know, the setState will be called to update the state, but instead of re-rendering it will then call the callback function thus the button is not disabled while the timer counts down.

it will be disabled after the timer, not before, where as I want it before, not after.

like image 323
TheWebs Avatar asked Mar 04 '19 01:03

TheWebs


1 Answers

I suspect something else is causing you issue. This code seems to be working the way you want (or I'm misunderstanding).

https://codesandbox.io/s/8nz508y96j - button click disables the button and post alert appears 3 seconds later

Though using componentDidUpdate is the recommended approach..

https://reactjs.org/docs/react-component.html#setstate

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

like image 134
lecstor Avatar answered Oct 26 '22 19:10

lecstor