Javascript Fundamentals · Data Fetching

Cancel a request with AbortController

AbortController

Cancel a request with AbortController

You start a request, then the situation changes — the user types a new query, navigates away, or the component unmounts. That first request keeps running. When its result arrives it can overwrite the fresher data already on screen.

You need a way to cancel work you no longer want. AbortController is the language's cancellation primitive. You create a controller, pass its signal to fetch, and call abort() when the work is no longer wanted:

const controller = new AbortController();

fetch(url, { signal: controller.signal })
  .then((response) => response.json())
  .catch((error) => {
    if (error.name === 'AbortError') return;
    throw error;
  });

controller.abort();

abort() makes the in-flight request reject with an AbortError — a DOMException whose name is 'AbortError' — so you catch it and ignore it rather than treating it as a failure. The same signal can be passed to several requests to cancel them together, and a signal that is already aborted when fetch is called rejects immediately.

You are about to answer a short quiz on AbortController.

  1. AbortController is the standard way to cancel an in-flight fetch request.
  2. Pass the controller's ___ to fetch to make the request cancellable.
  3. Calling controller.abort() makes an in-flight fetch reject.
  4. An aborted fetch rejects with an error whose name is ___.
  5. Passing a signal that is already aborted to fetch makes it reject immediately.
  6. fetch automatically cancels its request when a component unmounts.
  7. One AbortController's signal can be passed to ___ requests to cancel them together.