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);
For instance configuration:
import axios from "axios";
import withAbort from "axios-abort";
const axiosAbort = axios.create()
withAbort(axiosAbort);
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()
React hook
useEffect(() => {
let promise = axios.get("https://google.com")
promise.then().catch(error => {
console.error(error) // => error due to abort
})
return () => {
promise.abort()
};
}, []);
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]])
You also can customize supported methods list via options
parameter:
withAbort(axios, {
methods: ['get'] // only add abort controller into GET method
})
Thanks for reading and hope you like it 🙆
Top comments (0)