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]);
Answer from Sharon 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....
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();
Discussions

reactjs - how to cancel/abort ajax request in axios - Stack Overflow
I use axios for ajax requests and reactJS + flux for render UI. In my app there is third side timeline (reactJS component). Timeline can be managed by mouse's scroll. App sends ajax request for the More on stackoverflow.com
🌐 stackoverflow.com
react native - How to cancel axios request? - Stack Overflow
I know that I need to use CancelToken but I don't know how to pass it on my network layer Please help ... You might also want to look at debouncing your input. If a typical user types 4 characters before waiting to see what results come back, you're going to be aborting 75% of the requests you're ... More on stackoverflow.com
🌐 stackoverflow.com
react native - Cancel axios request, if response from server comes after 10 seconds - Stack Overflow
I am using axios in my react-native application to make api calls. What I need to do is to cancel the api request and show a Something went wrong screen if 10 seconds have passed and yet there is no 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
🌐
DEV Community
dev.to › serifcolakel › canceling-requests-in-reactreact-native-a-comprehensive-guide-2ami
Canceling Requests in React/React Native: A Comprehensive Guide - DEV Community
April 6, 2025 - This article dives into various ways to handle cancellation of requests in React and React Native, covering: Axios: Using CancelToken to cancel 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. In addition to cancelling requests, there are several other best practices you can employ to enhance your React application’s performance and maintainability.
🌐
CodePen
codepen.io › dashtinejad › pen › Lxejpq
React + axios (with cancellation)
class Repos extends React.Component { constructor(props) { super(props); this.state = {repos: []}; } fetchRepos() { // cancel the previous request if (typeof this._source != typeof undefined) { this._source.cancel('Operation canceled due to new request.') } // save the new request for cancellation this._source = axios.CancelToken.source(); axios.get(`https://api.github.com/users/${this.props.username}/repos`, // cancel token used by axios { cancelToken: this._source.token } ) .then(response => this.setState({ repos: response.data })) .catch(error => { if (axios.isCancel(error)) { console.log('
🌐
CodingDeft
codingdeft.com › posts › axios-cancel-previous-request-react
Cancelling previous requests in Search bar using Axios in React | CodingDeft.com
We are specifying a port here since json-server will use 3000 by default, which we will need for React! A delay of 3 seconds to simulate a slow API, so that we can cancel! Open the below URL in a browser and you should be able to see the response: ... An onChange handler for the input element called handleSearchChange which will be triggered every time we enter a text on the search bar. And finally, we are calling the API using Axios by passing the search term.
Find elsewhere
🌐
DEV Community
dev.to › nileshcodehub › how-to-cancel-api-calls-in-react-with-axios-a-step-by-step-guide-41b6
How to Cancel API Calls in React with Axios: A Step-by-Step Guide - DEV Community
March 7, 2025 - Learn how to manage multiple API calls in React by canceling previous requests with Axios. This guide shows you how to use Axios’s CancelToken to cancel requests that are no longer needed.
🌐
Medium
medium.com › @ali.abualrob2612 › optimizing-your-apps-with-axios-cancel-tokens-a-simple-guide-d27fbdbf4ada
Optimizing your Apps with Axios Cancel Tokens: A Simple Guide | by Ali Abualrob | Medium
October 7, 2024 - Handling network requests efficiently is critical when developing mobile apps, particularly in React Native. Without proper management, unnecessary requests can bog down your app, cause memory leaks, and hurt performance. Thankfully, Axios, a popular HTTP client, provides a feature called Cancel Tokens that allows you to cancel network requests when they are no longer needed.
🌐
DEV Community
dev.to › tmns › usecanceltoken-a-custom-react-hook-for-cancelling-axios-requests-1ia4
useCancelToken: a custom React hook for cancelling Axios requests - DEV Community
January 26, 2022 - How to create a custom React hook for cancelling Axios requests. Tagged with axios, react, hooks, javascript.
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-cancel-axios-requests-using-abortcontroller-in-react-and-react-native-the-easy-way-1d636e42f22d
How to Cancel Axios Requests Using AbortController in React and React Native(The Easy Way) | by Anson Mathew | JavaScript in Plain English
April 21, 2025 - Solution: Cancel old requests using AbortController. ... Make sure you’re using version 0.22.0 or later — it supports AbortController. ... New JavaScript and Web Development content every day.
🌐
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 - To use it: Instantiate a new controller object const controller = new AbortController(); Then create a signal that alerts the async action on when to terminate/abort its process. In case of a network request, this will signal the request to cancel.
🌐
GitHub
gist.github.com › 27dde226ecbc1c1bc384ffe7e8466169
An example of an Axios request that can be cancelled. · GitHub
March 19, 2022 - An example of an Axios request that can be cancelled. - AxiosCancelRequestExample.js
🌐
Stack Overflow
stackoverflow.com › questions › 70771357 › how-to-cancel-axios-request
react native - How to cancel axios request? - Stack Overflow
I know that I need to use CancelToken but I don't know how to pass it on my network layer Please help ... You might also want to look at debouncing your input. If a typical user types 4 characters before waiting to see what results come back, you're going to be aborting 75% of the requests you're ...
🌐
OpenReplay
blog.openreplay.com › how-to-cancel-requests-in-axios
How To Cancel Requests in Axios
April 18, 2023 - When a request gets canceled, a JavaScript AbortError is raised. This will be wrapped by Axios in a CanceledError. Use AbortController to cancel a request in Axios as in the example below:
🌐
Till it's done
tillitsdone.com › blogs › cancel-axios-requests-in-react
How to Cancel Axios Requests in React Guide - Tillitsdone
Learn how to effectively manage and cancel Axios requests in React applications using CancelToken and AbortController. Prevent memory leaks and handle race conditions like a pro.
🌐
CodeSandbox
codesandbox.io › s › cancel-requests-with-axios-reactjs-rrzej
Cancel requests with Axios - React.js - CodeSandbox
January 29, 2020 - Cancel requests with Axios - React.js by Cu3e using axios, react, react-dom, react-scripts
Published   Sep 30, 2019
Author   Cu3e
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Abort a Request While Navigating Away From the Component in React | Pluralsight
December 20, 2019 - To cancel an axios request, we first need to extract the cancel token from axios.CancelToken, get the source by calling the source() method of the cancel token, and then pass the source in the config of the axios call.