Cancel Axios Ajax Request Subsequent Request

If a user make two request in succession and you want to cancel the first, here’s how to do it in Axios.

// Configure
let call;
const once = (config = {}) => {
    if (call) {
      call.cancel("Only one request allowed at a time.");
    }
    call = axios.CancelToken.source();

    config.cancelToken = call.token
    return axios(config);
  }

// Call
var config = {
        method: "get",
        url: "/your/url/endpoint",
        timeout: 60000
      }

once(config)
        .then(response => {
          // success callback
        })
        .catch(error => {
          // error callback
        })
        .then(() => {
          // do no matter error or success
        });

Works like a charm. Provided by NicksonYap, some iteration of iterations.

https://github.com/axios/axios/issues/1361#issuecomment-417880626

Leave a Comment