Set State Twice In A Single Function - Reactjs
Solution 1:
As setState
are async in React you might not get updated state immediately but setState
gives you prevState
param in setState
function to get last updated state so you won't merge state
The syntax goes like this in your case
this.setState((prevState) => { hidden: false }, () => {
setTimeout(() => {
this.setState({ hidden: !prevState.hidden });
}, 500);
});
just update your value to the updated state using prevState
If I understand your problem correct this should work fine Please let me know if more clarification required
Solution 2:
If you try something like that:
constshowAnimation = () => {
this.setState({ hidden: false }, () => {
setTimeout(() => {
this.setState({ hidden: true });
}, 500);
}
}
Solution 3:
I would personally use animations within JS if you are looking to time it without setTimeout. However this may be down to the face that 'setState' is async within react.
similar : Why is setState in reactjs Async instead of Sync?
However react does expose a callback within setState - this works for me
this.setState(
{ hidden : false },
() => {
setTimeout(()=>{this.setState({hidden : true})}, 500)
}
);
Solution 4:
For rendering performance, react batches calls to setState
such that sequential calls will be executed together and will often be reflected in the same render cycle. Per the docs:
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.
In order to ensure that the first setState has been executed prior to your second call, you can pass setState
a callback as the second argument. It's not perfect, but something like the following will ensure that your second call to setState
will only happen once hidden: false
.
constshowAnimation = () => {
this.setState({ hidden: false }, () =>setTimeout(() => {
this.setState({ hidden: true });
}, 500););
};
Post a Comment for "Set State Twice In A Single Function - Reactjs"