DEV Community

Cover image for How to stop or abort a fetch request in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to stop or abort a fetch request in JavaScript?

Originally posted here!

To stop or abort a fetch request, you have to use the AbortController API. This helps to stop the fetch request from the client-side only but not on the server-side. The server continues to process the request even after the request is stopped from the client-side.

Let's see this in action.

First, we need to create an object of AbortController.

// create an object of AbortController
const controller = new AbortController();
Enter fullscreen mode Exit fullscreen mode

Then we need to get the signal property from the controller object and pass it as an option to the fetch request as an option.

// create an object of AbortController
const controller = new AbortController();

// get the signal property from the controller
const signal = controller.signal;
Enter fullscreen mode Exit fullscreen mode

Pass the signal property as an option to the fetch request.

The signal property is a Read-only property.

Let's use an API endpoint from JSONPlaceholder website for the fetch request.

// create an object of AbortController
const controller = new AbortController();

// get the signal property from the controller
const signal = controller.signal;

// fetch request
// passing signal as an option
fetch("https://jsonplaceholder.typicode.com/posts", { signal })
  .then((response) => response.json())
  .then((json) => console.log(json));
Enter fullscreen mode Exit fullscreen mode

We have now configured the fetch request to use the AbortController.

Now to stop the ongoing fetch request we have to use the abort() method in the controller object.

// To stop the ongoing fetch request
controller.abort();
Enter fullscreen mode Exit fullscreen mode

To see the working example see JSBin.

Feel free to share if you found this useful 😃.


Top comments (0)