Sometimes, we want to wait for setState to finish before triggering a function with React.js.
In this article, we’ll look at how to wait for setState to finish before triggering a function with React.js.
How to wait for setState to finish before triggering a function with React.js?
To wait for setState to finish before triggering a function with React.js, we call setState
with a callback that runs after the state is updated as the 2nd argument.
For instance, we write
this.setState(
{
originId: input.originId,
destinationId: input.destinationId,
radius: input.radius,
search: input.search,
},
this.findRoutes
);
to call setState
with an object to update the states.
The 2nd argument is the this.findRoutes
method that runs when we finished updating the states.
We call this.setState
in a method to update the states.
Conclusion
To wait for setState to finish before triggering a function with React.js, we call setState
with a callback that runs after the state is updated as the 2nd argument.
One reply on “How to wait for setState to finish before triggering a function with React.js?”
How do we do the same with react hooks?