DEV Community

Quy Luong
Quy Luong

Posted on

Abort an Axios request with a simple library

TL;DR

Starting from v0.22.0 Axios supports AbortController to cancel requests. But it requires lots of steps to handle AbortController in every Axios request.

So, I just write a simple library axios-abort to implement it with no code changes.

Installation

npm install axios-abort --save

Notice: Make sure you are using Axios v0.22.0 or higher

Usage

Small configuration

In your axios configuration file:

For global configuration:

import axios from "axios";
import withAbort from "axios-abort";

withAbort(axios);
Enter fullscreen mode Exit fullscreen mode

For instance configuration:

import axios from "axios";
import withAbort from "axios-abort";

const axiosAbort = axios.create()
withAbort(axiosAbort);
Enter fullscreen mode Exit fullscreen mode

Now, all axios request promises will contain abort() function. You can use it to abort a request.

Node.js

let promise = axios.get("https://google.com")

promise.then().catch(error => {
        console.error(error) // => error due to abort
    })

promise.abort()
Enter fullscreen mode Exit fullscreen mode

React hook

useEffect(() => {
    let promise = axios.get("https://google.com")

    promise.then().catch(error => {
        console.error(error) // => error due to abort
    })

    return () => {
        promise.abort()
    };
}, []);

Enter fullscreen mode Exit fullscreen mode

Supported Methods

axios-abort supports methods below:

axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
Enter fullscreen mode Exit fullscreen mode

You also can customize supported methods list via options parameter:

withAbort(axios, {
    methods: ['get']    // only add abort controller into GET method
})
Enter fullscreen mode Exit fullscreen mode

Thanks for reading and hope you like it 🙆

Top comments (0)