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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With