Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React wait for a specific response from API

I have a page that waits for a specific status from the server.

The thing is, that the server has statuses - (Enabled, In_Progress, Disabled), and it returns 200 also for In_Progress.

I thought about async but the problem is that the server will return a response in case of In_Progress.

Is there any way to wait until the API will return "Enabled"? Or I have to send a request every X seconds?

EDIT

I have an option to change the response (502 instead of 200) on the server-side if it helps.

Thanks

like image 852
Dvi N Avatar asked Aug 04 '20 09:08

Dvi N


People also ask

Can you use fetch in React?

Using the useFetch custom Hook from react-fetch-hook However, we can go a step further by simplifying data fetching using the useFetch Hook from the react-fetch-hook library. This is a custom Hook that allows us to reuse the fetching logic in the same or different components of our app. It doesn't get simpler.

Does React use REST API?

You can consume REST APIs in a React application in a variety of ways, but in this guide, we will look at two of the most popular approaches: Axios (a promise-based HTTP client) and Fetch API (a browser in-built web API).


1 Answers

This heavily depends on the implementation of this service side API. In a ideal situation something like Websockets or Server side events are used. This basically means that the server will let the client (React) know when it is ready.

In you situation, sending multiple requests until the status is Enabled is properly the best solution. You can implement with setInterval and clearInterval. Something like this:

const pollInterval = setInterval(() => {
   let result = doRequest();
   if (result == "Enabled") {
      this.setState({ ready: true }, () => {
          clearInterval(pollInterval)
      });
   }
}, 1000); // The interval is in milliseconds, so 1000ms = 1s
like image 183
n9iels Avatar answered Oct 07 '22 06:10

n9iels