How to cancel a fetch request in javascript? Let's find out

using `AbortController` interface to cancel fetch request

Introduction:

Ever wonder how to cancel the request when the user navigates to the gallery or some other resource-heavy page of your web application or web page and as soon as he taps the link to navigate the page you start fetching the request very nice but wait now the user navigate to some other page and you start the network request of the resources of that page but what happens to the previous request, let me tell you it's still going on and in this article, we will find out how to cancel this request, so let's start!

The Fetch API:

If you are developing websites for more than 2 months then you might come across fetch API in javascript which lets you create async requests from the browser, if you look closely at the syntax of the fetch API then you notice something strange

fetch(url,{data})
.then((res,rej) => { 
// handling the data
})
.catch(err=> console.log(err));

this object which we call the init object lets you specify additional settings for the request and guess what this is the key to our fetch request abortion.

AbortController:

If you are new to javascript then you may not hear about AbortController which lets you create an object which can abort a network request in javascript the syntax looks something like this


// first we will create an object of this interface
const controller = new AbortController();

//then we will create save the reference of the signal of the controller to pass to the fetch API
const signal = controller.signal;

Finally:

Now we can pass this signal to the fetch API inside the init object like this

fetch(url , {signal})
.then((res,rej) => { 
// handling the data
})
.catch(err=> console.log(err));

and then we can call controller.abort() wherever certain condition fulfills to cancel our fetch request.

Summary:

And that's it now you have full control over your fetch request. The AbortController interface is rarely used but it could be useful in certain conditions. Thanks for reading.