You can use cancellation

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
Answer from Tony on Stack Overflow
🌐
Axios
axios-http.com › docs › cancellation
Cancellation | Axios Docs
function newAbortSignal(timeoutMs) ... //Aborts request after 5 seconds }).then(function(response) { //... }); You can also cancel a request using a CancelToken....
Discussions

Cancel all pending axios request on error
I'm currently working in a Vue3 application using Axios. Basically my use case is that I have a global loading indicator that is activated using a request interceptor and then deactivated in the re... More on stackoverflow.com
🌐 stackoverflow.com
How do I cancel all pending Axios requests in React Native? - Stack Overflow
If you are doing it for POST request, note that you need to pass cancel token source as third argument 2022-03-08T13:47:45.537Z+00:00 ... @Kapobajza I see, thanks, I didn't realize it got deprecated. I've been using the older version of axios and this method worked fine for me. More on stackoverflow.com
🌐 stackoverflow.com
How to cancel all prior requests and only display results from the latest API call.
You want to look up the Abort Controller API . It will let you cancel fetch requests that are in flight. What you can do is keep a reference to the controller while you are waiting for a response. If a new request is made you use the controller to cancel the old one. More on reddit.com
🌐 r/reactjs
71
55
June 28, 2021
Cancel Request if a subsequent request is made?
Summary Hello, I am trying to use Axios to implement a search function on my website. The issue I'm having is due to race conditions. When the user searches for "*" it returns all the results in th... More on github.com
🌐 github.com
15
February 13, 2018
🌐
OpenReplay
blog.openreplay.com › how-to-cancel-requests-in-axios
How To Cancel Requests in Axios
April 18, 2023 - Then, its signal property is passed to the Axios signal config in a cancellable HTTP GET request. When calling the abort() method on the controller, all pending HTTP requests involving that signal will be canceled.
🌐
Medium
medium.com › @usman_qb › cancel-all-axios-requests-on-page-change-in-spa-eb8adfef79a9
Cancel all axios requests on page change in SPA | by Usman N. | Medium
May 11, 2022 - Let’s say we move from /page1 to /page2. cancelPreviousPageRequests(“/page1”) takes the previousPath, finds a property called “/page1” in axiosInstances, then calls abort() on its controller property.
🌐
Stack Overflow
stackoverflow.com › questions › 76583665 › cancel-all-pending-axios-request-on-error
Cancel all pending axios request on error
Pass cancelToken with API call, if any call gets cancelled all pending requests will stop by calling source.cancel · import { ref } from 'vue'; import axios from 'axios'; export default { setup() { const cancelToken = axios.CancelToken; const ...
🌐
npm
npmjs.com › package › axios-cancel
axios-cancel - npm
December 17, 2016 - console.log('request 2 cancelled'); } else { console.log('some other reason'); } }); axios.cancelAll(); // aborts all HTTP request, and cancels all promises · // logs `request 1 cancelled` // logs `request 2 cancelled` axiosCancel(instance: ...
      » npm install axios-cancel
    
Published   Dec 17, 2016
Version   0.2.2
Author   Thaer Abbas
🌐
Medium
julietonyekaoha.medium.com › react-cancel-all-axios-request-in-componentwillunmount-e5b2c978c071
Cancel all axios requests in React’s componentWillUnmount Lifecycle. | by Juliet Onyekaoha | Medium
May 11, 2022 - This means that if we have more than one API request in our component(regardless of the method, POST, GET, DELETE e.t.c), we can use one source variable to cancel all the requests.
🌐
Apidog
apidog.com › blog › axios-cancel-requests
How to cancel API requests with Axios
February 9, 2026 - That's where axios cancel requests come into play! So, how does this canceling thing work? Well, the key lies in the CancelToken provided by Axios. This token allows you to create a "cancelable operation" and associate ...
Find elsewhere
Top answer
1 of 2
1

In myApi I used AbortController to ensure that any cancellable requests are aborted when a new cancellable request comes in:

let controller = new AbortController();

class client {
  axiosClient = axios.create({
    baseURL: example.com,
  });

  async post(url, data, config, stoppable) {
    let newConfig = {...config};

    // If this call can be cancelled, cancel any existing ones
    // and set up a new AbortController
    if (stoppable) {
      if (controller) {
        controller.abort();
      }
      // Add AbortSignal to the request config
      controller = new AbortController();
      newConfig = {...newConfig, signal: controller.signal};
    }
    return this.axiosClient.post(url, data, newConfig);
  }
}

export default new client();

Then in my component I pass in 'stoppable' as true; after the call I check whether the call was aborted or not. If not, I show the results; otherwise I ignore the response:

  useEffect(() => {
    const load = () => {

      const url = '/getDataForDate';

      const req = {
        selectedDate: moment(dateState.currentDate).format(
          'YYYY-MM-DD',
        ),
      };

      myApi
        .post(url, req, null, true)
        .then((res) => {
          if (!res.config.signal.aborted) {
            // Do something with the results
          }
        })
        .catch((err) => {
// Show an error if the request has failed entirely
        });
    };

    load();
  }, [dateState.currentDate]);
2 of 2
0

Step1: Generate cancel token

const cancelTokenSource = axios.CancelToken.source();

Step2: Assign cancel token to each request

axios.get('example.com/api/getDataForDate', {
  cancelToken: cancelTokenSource.token
});

// Or if you are using POST request

axios.post('example.com/api/postApi', {data}, {
  cancelToken: ancelTokenSource.token,
});

Step3: Cancel request using cancel token

cancelTokenSource.cancel();
🌐
Andrewjamesbibby
blog.andrewjamesbibby.com › 2019 › 08 › 01 › cancel-all-pending-axios-requests-in-vue-spa-on-router-change
Cancel all pending axios requests in Vue SPA on router change – <code>
August 1, 2019 - This will hold all created axios cancel tokens. The tokens are created via the ADD_CANCEL_TOKEN mutation. The action CANCEL_PENDING_REQUESTS when dispatched will go through the cancelTokens array and cancel all pending requests before emptying the array via CLEAR_CANCEL_TOKENS mutation.
🌐
Till it's done
tillitsdone.com › blogs › cancel-axios-requests-in-react
How to Cancel Axios Requests in React Guide - Tillitsdone
Axios provides a powerful feature called Cancel Tokens that allows us to cancel pending requests.
🌐
Plain English
plainenglish.io › blog › how-to-cancel-fetch-and-axios-requests-in-react-useeffect-hook
How to Cancel Fetch and Axios Requests in React’s useEffect Hook
October 20, 2023 - This code achieves the same functionality as the Fetch example but with Axios and request cancellation using an AbortController equivalent (axios.CancelToken). Here is the final result. Now you can see how our application has been improved; the browser only handles the last request and cancels any previous requests that were pending before the current one. The AbortController interface is supported by all modern browsers and other HTTP clients such as Fetch or node-fetch.
🌐
GitHub
github.com › axios › axios › issues › 1361
Cancel Request if a subsequent request is made? · Issue #1361 · axios/axios
February 13, 2018 - The way I can think about how to do this is to issue a cancel token for every request, and before a request is made, the system will try to cancel any previous requests. The issue I'm having is when I try to use the cancel token, it cancels ...
Author   ChadTaljaardt
🌐
CodingDeft
codingdeft.com › posts › axios-cancel-previous-request-react
Cancelling previous requests in Search bar using Axios in React | CodingDeft.com
This can be done by storing a reference to the Axios call in a variable and canceling whenever a new request is triggered. ... For our demonstration let's set up a json-server Install the json-server globally.
🌐
Mastering JS
masteringjs.io › tutorials › axios › cancel
Axios Cancel Request - Mastering JS
November 23, 2020 - That's because there's no way to cancel an HTTP request in general once the request has already been sent over the network. If Axios has already sent the request, all cancel does is cause your Axios request to error out and ignore any response ...
🌐
GitHub
github.com › axios › axios › issues › 80
Is it possible to cancel axios requests? · Issue #80 · axios/axios
July 23, 2015 - I'm building something similar to search lookahead, and with each change event to a text input I want to fire off a new set of axios get requests. When the change event occurs, I need to cancel all uncompleted axios requests from the last change event (as they will no longer be needed)...
Author   paulwehner
🌐
DEV Community
dev.to › collegewap › cancelling-previous-requests-in-search-bar-using-axios-in-react-3nef
Cancelling previous requests in Search bar using Axios in React - DEV Community
August 21, 2021 - And finally, we are calling the API using Axios by passing the search term. Now if we try searching for cat we will see that 3 different calls made and all 3 responses are logged. We really don't need the previous 2 responses, which we can cancel when the next request is made. ... let cancelToken; const handleSearchChange = async (e) => { const searchTerm = e.target.value; //Check if there are any previous pending requests if (typeof cancelToken != typeof undefined) { cancelToken.cancel("Operation canceled due to new request."); } //Save the cancel token for the current request cancelToken = a
🌐
DevPress
devpress.csdn.net › react › 6317cf33237eb178e9dfc84d.html
Cancelling previous requests in Search bar using Axios in React_rAc-React
And finally, we are calling the API using Axios by passing the search term. Now if we try searching for cat we will see that 3 different calls made and all 3 responses are logged. We really don't need the previous 2 responses, which we can cancel when the next request is made. ... let cancelToken; const handleSearchChange = async (e) => { const searchTerm = e.target.value; //Check if there are any previous pending requests if (typeof cancelToken != typeof undefined) { cancelToken.cancel("Operation canceled due to new request."); } //Save the cancel token for the current request cancelToken = a