React wait for a specific response from API

Viewed 1196

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

2 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

I would use something like below:

const useStatusServer = ({ pollingInterval }) => {
  const [status, setStatus] = useState();
  useEffect(() => {
     const interval = setInterval(() => {
      axios.get('blabla url')
        .then(({ status }) => {
            setStatus(status);
            if (status === "Enabled") {
                clearInterval(interval); // optional poll deactivation
            }
        });
    }, pollingInterval);
    return () => {
       clearInterval(pollingInterval);
    };
  }, [pollingInterval]);
  return { status };
};

Now you can use this hook in one of the component where you want to retrieve that value from with:

const { status } = useStatusServer(1000); // timeout in ms

If you need to use more than one time above hook, I would transform it to a context with constate or hoist the hook to ancestors so that you can pass down the value as props to multiple children

Related