Axios does not support canceling requests at the moment. Please see this issue for details.

UPDATE: Cancellation support was added in axios v0.15.

EDIT: The axios cancel token API is based on the withdrawn cancelable promises proposal.

UPDATE 2022: Starting from v0.22.0 Axios supports AbortController to cancel requests in fetch API way:

Example:

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()
Answer from Nick Uraltsev 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 axios get request when typing reactjs - Stack Overflow
I'm creating an autocomplete function, so basically whenever I type on search box it will cancel the previous http get request. I checked the jQuery ui autocomplete and that's what they did. Is that More on stackoverflow.com
🌐 stackoverflow.com
August 7, 2019
How to cancel all setState and axios calls when component unmounts
The real question is, why is your component unmounted before your axios calls are finished? Is it in a modal that is being closed and destroyed? You should be waiting for your requests to finish up before your component unmounts. More on reddit.com
🌐 r/reactjs
4
1
August 4, 2022
How to cancel Axios requests in React with redux?
Usually I would call abort() on the action (or thunk if async). It will cancel the action from being passed to the reducer but the HTTP request will still complete. https://redux-toolkit.js.org/api/createAsyncThunk#canceling-while-running EDIT: Though it seems if you're doing a search functionality that you'll want to use a debounce method so you don't send a request on every keydown, but rather after the user stops typing after a certain amount of time. More on reddit.com
🌐 r/webdev
5
2
January 29, 2022
Axios Interceptors, catching the request too late!
If this help. When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay in the execution of your axios request when the main thread is blocked (a promise is created under the hood for the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag to the options object that will tell axios to run the code synchronously and avoid any delays in request execution. axios.interceptors.request.use(function (config) { config.headers.test = 'I am only a header!'; return config; }, null, { synchronous: true }); Try to set this at first part: axios.interceptors.request.use(function (config) { return { ...config, url: getBaseUri() + config.url } }, null, { synchronous: true }) More on reddit.com
🌐 r/reactjs
2
2
December 4, 2021
🌐
CodingDeft
codingdeft.com › posts › axios-cancel-previous-request-react
Cancelling previous requests in Search bar using Axios in React | CodingDeft.com
The solution here is to cancel the previous request. This can be done by storing a reference to the Axios call in a variable and canceling whenever a new request is triggered.
🌐
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.
🌐
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.
🌐
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 - Inside the axios-request.js file, we’re exporting out an object called apiRequestsFormat , that holds a key getRequest which is a function that takes the urland cancelToken. On line 5, the cancelToken is passed into the config object which is further passed into the axios get call along with the url.
🌐
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.
Find elsewhere
🌐
OpenReplay
blog.openreplay.com › how-to-cancel-requests-in-axios
How To Cancel Requests in Axios
April 18, 2023 - This approach was deprecated with Axios v0.22.0 in October 2021, and you should no longer use it. Yet, considering Axios’s popularity, some legacy apps may still rely on an older version. So, it is still worth mentioning it. You can cancel an HTTP request in Axios with CancelToken as in the example below:
🌐
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('
🌐
Since1979
since1979.dev › home › cancel axios request to prevent react from yelling at you. - since1979
Cancel Axios request to prevent React from yelling at you | Since1979.dev
June 17, 2020 - Inside this function we call the cancel method on our source object and we pass it a little message saying why the request got canceled. This message is passed to the error object in our catch block, so that is what will get logged out there.
🌐
YouTube
youtube.com › watch
Cancelling previous requests in Search bar using Axios in React - YouTube
Tutorial on how to cancel previous requests in in a search bar using Axios in React.db.json: https://github.com/collegewap/axios-api/blob/main/db.jsonSource ...
Published   August 21, 2021
🌐
Apidog
apidog.com › blog › axios-cancel-requests
How to cancel API requests with Axios
March 22, 2024 - You can then use this axiosInstance throughout your application for making API requests, and it will automatically handle cancel requests for you. In some cases, you might have multiple cancellable requests in a single component or function. To handle this situation, you can use an array or object to store multiple CancelToken instances. Here's an example of how you can manage multiple cancel requests: import React, { useState, useEffect } from 'react'; import axios from 'axios'; const MultipleRequests = () => { const [cancelTokens, setCancelTokens] = useState({}); const fetchData = (endpoint)
🌐
DevPress
devpress.csdn.net › react › 6317cf33237eb178e9dfc84d.html
Cancelling previous requests in Search bar using Axios in React_rAc-React
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: ... import axios from "axios"; import React from "react"; import "./App.css"; function App() { const handleSearchChange = async (e) => { const searchTerm = e.target.value; const results = await axios.get( `http://localhost:4000/animals?q=${searchTerm}` ); console.log("Results for " + searchTerm + ": " + results.data); }; return ( <div style={{ marginTop: "3em", textAlign: "center" }}> <input style={{ width: "60%", height: "1.5rem" }} type="text" placeholder="Search" onChange={handleSearchChange} /> </div> ); } export default App;
🌐
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 - 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: ... import axios from "axios"; import React from "react"; import "./App.css"; function App() { const handleSearchChange = async (e) => { const searchTerm = e.target.value; const results = await axios.get( `http://localhost:4000/animals?q=${searchTerm}` ); console.log("Results for " + searchTerm + ": " + results.data); }; return ( <div style={{ marginTop: "3em", textAlign: "center" }}> <input style={{ width: "60%", height: "1.5rem" }} type="text" placeholder="Search" onChange={handleSearchChange} /> </div> ); } export default App;
🌐
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 - Now we know that each page uses its own axios instance but how does it cancel all API calls when user moves to next page? For that, let’s go back to the app.js file. First of all we have two variables previousPath and currentPath. React-router-dom can notify us when the path/route changes but it can’t tell us about the previous path so we are maintaining this info on our own.
Top answer
1 of 6
36

Since axios v0.15 you can cancel request:

You can also create a cancel token by passing an executor function to the CancelToken constructor:

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

For more information please have a look Cancellation. And according to your code:

import React from 'react'
import axios from 'axios';

export function autocompleteSearchTest(value) {
    if (cancel != undefined) {
        cancel();
    }
    return axios.get(`https://jqueryui.com/resources/demos/autocomplete/search.php`, {
        cancelToken: new CancelToken(function executor(c) {
            // An executor function receives a cancel function as a parameter
            cancel = c;
        }),
        params: {
            q: value
        }
    })
        .then(response => {
            return response.data.response;
        })
        .catch(error => {
            const result = error.response;
            return Promise.reject(result);
        });
}

var CancelToken = axios.CancelToken;
var cancel;

export class AutoComplete extends React.Component {

    constructor() {
        super()
        this.state = {
            search: ''
        };
        this.handleSearchChange = this.handleSearchChange.bind(this);
    }

    handleSearchChange(event) {
        const target = event.target;
        const value = target.value;
        this.setState({
            search: value
        });
        autocompleteSearchTest(value)
    }

    render() {
        return (
            <div className="App-intro Dialog-section">
                <h2>AutoComplete</h2>
                <div className="form-control">
                    <label htmlFor="password">Lookup :</label>
                    <input name="search" type="text" value={this.state.search}
                           onChange={this.handleSearchChange}
                           id="password" ref="password" placeholder="Enter line"/>
                </div>
            </div>
        )
    }
}

export default AutoComplete;

And here it's

2 of 6
2

use: react, axios and redux-axios-middleware

user actions:

import axios from 'axios';
import * as type from 'constants/user';

const CancelToken = axios.CancelToken;
let cancel;

export const addUser = (data) => {
  if (cancel !== undefined) cancel();

  return ({
    types: [type.ADD_USER_REQUEST, type.ADD_USER_SUCCESS, type.ADD_USER_FAILURE],
    payload: {
      request: {
        url: '/api/user',
        cancelToken: new CancelToken(c => cancel = c),
        method: 'POST',
        data,
      },
    },
  });
};
🌐
Medium
medium.com › @iamyashkhandelwal › how-to-cancel-api-requests-using-axios-in-javascript-1b6d42084b43
How to cancel API requests using Axios in Javascript? | by Yash Khandelwal | Medium
July 29, 2023 - axios .get('https://api.example.com/data', { cancelToken: source.token, timeout: timeoutDuration || 2000, // time in ms }) .then((response) => { // Process the response data here }) .catch((error) => { if (axios.isCancel(error)) { console.log('Request canceled:', error.message); } else if (error.code === 'ECONNABORTED') { // timeout handling console.log('Request timed out'); } else { console.log('Error:', error.message); } }); Note: You do not need step-3 in-case you just want to add a timeout in your API calls, since the API call will get cancelled automatically once the timeout expires (only in-case the API hasn’t responded till then). Happy Coding! Optimization · API · Axios · JavaScript · Web Development · 127 followers · ·4 following · Front-end Engineer | ReactJS | NextJS | CMS | CDN | Web applications | Javascript ·
🌐
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
🌐
YouTube
youtube.com › watch
Cancelling an Axios request in a useEffect hook - YouTube
This video shows how to cancel an Axios request before it completes. We'll use a useEffect hook and it's cleanup function to help us accomplish this.Source c...
Published   February 19, 2019
🌐
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