JavaScript·100 questions

How to cancel a fetch request?

Answer

Modern web applications often face the need to cancel network requests that have become outdated. For example, a user types text into a search bar, and a request is sent to the server for each typed character. Previous requests thus lose relevance, but continue to burden the network and the server. To solve this problem, the built-in AbortController mechanism standard in modern browsers is used.

The first step to implement request cancellation is to create an instance of this class. You declare a constant, for example, const controller = new AbortController(). This object manages the cancellation process and contains a special signal.

The second step is to pass this signal into the parameters of the fetch function. You call fetch(url, { signal: controller.signal }), thereby linking the network request with the created controller. Now the browser knows that this request is under the control of this controller.

When the need arises to cancel an operation, such as when destroying a React component or launching a new search query, you call the controller.abort() method. This action instantly interrupts the execution of the network request at the browser level.

An important aspect is handling this event in code. When cancelled, fetch throws a DOMException of type AbortError. To prevent the application from crashing with an unhandled error, the code should be wrapped in a try/catch block or use the .catch() promise chain, where you must check the error type. If the error is an instance of DOMException and its name is AbortError, you can simply ignore it, since the cancellation was planned. This approach allows you to significantly save user traffic and improve overall interface responsiveness.

Was this answer helpful?

More questions in this topic

Related questions from other topics