HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Abort a fetch request in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
fetchjavascriptabortrequest

Problem

The Fetch API is nowadays the de facto way to send asynchronous requests in JavaScript. This is in part due to the fact that the fetch() method accepts a multitude of useful options. One of these is the signal option, which can be used to abort a request. To create a valid value for this option, you can use AbortController.signal after creating a new instance of AbortController. Then, you can use AbortController.abort() to cancel the request at any time.
This is particularly useful in scenarios where a request takes too long or the response is no longer needed. You can see a common React use-case for this in the useFetch hook.

Solution

// Create the AbortController
const controller = new AbortController();
const { signal } = controller;

// Perform the request
fetch('https://my.site.com/data', { signal }).then(res => console.log(res));

// Abort the request
controller.abort();

Code Snippets

// Create the AbortController
const controller = new AbortController();
const { signal } = controller;

// Perform the request
fetch('https://my.site.com/data', { signal }).then(res => console.log(res));

// Abort the request
controller.abort();

Context

From 30-seconds-of-code: abort-fetch

Revisions (0)

No revisions yet.