1

Let us say I am making multiple API calls from a React application. "Multiple API Calls" in this context means: Clicking on a checkbox several time fast. Everytime a checkbox is checked, an API call is triggered.

To illustrate this situation more precisely, I will add a screenshot off the User Interface:

Based on the above description, I am clicking at master several times. I am not even waiting for the response from the API

Everytime a checkbox is checked, this function is called:

export function getApplications(authenticationToken, url, query, queryStringIn) {
return function(dispatch) {
    const config = {
        headers: {'Authorization' :"Bearer " + authenticationToken}
    };

    let queryString;

    if (queryStringIn === "" || queryStringIn === null) {
        queryString = queryStringBuilder.buildQuery(query);
    } else {
        queryString = queryStringIn;
    }

    let fetchTask =  fetch(url + "/Applications?" + queryString.toString(), config).then(data => {
        return data.json();
    }).then(applications => {
        dispatch(loadApplicationsSuccess(applications, queryString, query));
    }).catch(error => {
        dispatch(loadApplicationsFailed(error));
    });
    addTask(fetchTask); //ensure that server rendering is waiting for this to complete
    return fetchTask;
}

The problem occurs when I am clicking at a checkbox so fast that the API is not able to return a response, before I am making a new call to the same API.

I want a behavior where only the last API call is made, and API calls in the queue before are cancelled if there are any.

What do you guys recommend to do in a such case?

Jagjit Singh
  • 661
  • 9
  • 16
  • you can't reliably abort a request because the server may have already gotten it. you could try throttling/debouncing. – Daniel A. White Jan 19 '17 at 15:54
  • why not disable the check box on the first click, then enable some time later, say 1000 ms? – Cruiser Jan 19 '17 at 15:56
  • This [question and answer](http://stackoverflow.com/questions/41405832/how-to-implement-cancellable-ordered-promises/41406155#41406155) might be what you're looking for. Because you are using promises returned from fetch, you can resolve promises from the past with a `noop`. – KevBot Jan 19 '17 at 16:00
  • Make a variable named `loading`, set it to `true` when your request starts, set it to `false` when your request is done. Whenever you make a new request, check that `loading` is `false` first. – damd Jan 19 '17 at 16:02
  • [`axios`](https://github.com/mzabriskie/axios#cancellation) supports cancel-able request. By cancel, it simply means that the callback will not be executed – xiaofan2406 Jan 20 '17 at 00:06

0 Answers0