Categories
React Answers

How to wait for setState to finish before triggering a function with React.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to wait for setState to finish before triggering a function with React.js?”

Leave a Reply

Your email address will not be published.