Aborting/Cancelling requests with Axios

Learn how to cancel requests using Axios cancel token

Riya Varyani
2 min readMay 13, 2021

Have you ever wondered that while you are searching something through a search bar, the result starts showing up as soon as you start typing, how?

Probably because the request was already sent while you were typing. That means whenever you are typing a character, Axios is sending a new request along with that new character. But we don’t need those previous requests so we cancel them.

Why do we need to cancel?

Apart from the obvious reason for saving the resources, there is one more reason for cancelling, that is, if the response of the first request arrives after the response of the second request, then we might render inconsistent data.

Let’s start !

For cancelling a request, we need to create cancel token using the CancelToken.source() by axios.

useEffect(() => {
const cancelToken = axios.CancelToken.source()
.
.

The CancelToken.source() provides us with two main requirements for cancelling the Axios request, the cancel token and the cancel() function.

We need to pass the cancel token as a config to the axios.get() function and call the cancel() function whenever we need to cancel the previous Axios request.

.
.
axios.get( BASE_URL ,{
cancelToken: cancelToken.token,
//params
}).then(//OnResolved code here).catch(err => {
if(axios.isCancel(err)) console.log(err.message);
})
return() => {
cancelToken.cancel()
}
.
.
}

Now, this happens when two requests are made subsequently.

The first request is cancelled

This way, each request will be automatically cancelled when a new one of the same type is made.

Thanks for reading :)

--

--