Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout on Axios Requests

Our site currently has a filter feature that fetches new data via axios depending on what is being filtered.

The issue is that the filter is done on real time and every change made via react causes an axios request.

Is there a way to put a timeout on the axios request so that I only fetch the last state?

like image 827
lost9123193 Avatar asked Mar 06 '23 09:03

lost9123193


2 Answers

I would suggest using debounce in this case to trigger API call after a specified millisecond of user input.

But just in case you need to add a timeout during axios call, this can be achieved like -

instance.get('/longRequest', {
  timeout: 5000
});
like image 134
Satyaki Avatar answered Mar 21 '23 09:03

Satyaki


The problem has two parts.

The first part is debouncing and is default for event listeners that can be triggered often, especially if their calls are expensive or may cause undesirable effects. HTTP requests fall into this category.

The second part is that if debounce delay is less than HTTP request duration (this is true for virtual every case), there still will be competing requests, responses will result in state changes over time, and not necessarily in correct order.

The first part is addressed with debounce function to reduce the number of competing requests, the second part uses Axios cancellation API to cancel incomplete requests when there's a new one, e.g.:

  onChange = e => {
    this.fetchData(e.target.value);
  };

  fetchData = debounce(query => {
    if (this._fetchDataCancellation) {
      this._fetchDataCancellation.cancel();
    }

    this._fetchDataCancellation = CancelToken.source();

    axios.get(url, {
      cancelToken: this._fetchDataCancellation.token
    })
    .then(({ data }) => {
      this.setState({ data });
    })
    .catch(err => {
      // request was cancelled, not a real error
      if (axios.isCancel(err))
        return;

      console.error(err);
    });
  }, 200);

Here is a demo.

like image 39
Estus Flask Avatar answered Mar 21 '23 09:03

Estus Flask