Prevent axios from making more than one request to a specific endpoint at the same time

Viewed 935

In my React application, users can scroll down in the table and when they are almost at the bottom, the table fires requests to load subsequent data. My goal is to limit axios from making more than 1 subsequent data request at the same time. I tried to limit duplicate requests being fired by this condition:

if (!isLoading) { // isLoading is set to true in the requestData method
   requestData();
}

but it's not enough, if users scroll fast multiple requests go out until isLoading is set to true.

I found that the axios interceptors might be a solution. So currently I'm using this code to prevent making more than 1 request:

let subsequentDataRequestInProgress = false;

apiClientQESubsequentRequest.interceptors.request.use((request) => {
    if (subsequentDataRequestInProgress) { // if there's a pending request, don't send another one
      return Promise.reject('Duplicate request.');
    } else {
      subsequentDataRequestInProgress = true;
    }
  return request;

}, (error) => {
  return Promise.reject(error);
});

apiClientQESubsequentRequest.interceptors.response.use((response) => {
  // got a response, we're able to handle another request
  subsequentDataRequestInProgress = false;
  return Promise.resolve(response)
}, (error) => {
  return Promise.reject(error);
});

export { apiClientQESubsequentRequest };

Is there a better solution to solve my problem? Do you think this is a reasonable solution?

0 Answers
Related