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.