Cancelling Requests
AbortController lets you cancel fetch requests and other async operations by signalling an AbortSignal.
AbortController lets you cancel fetch requests and other async operations by signalling an AbortSignal.
const ctrl = new AbortController();
const { signal } = ctrl;
const timer = setTimeout(() => ctrl.abort(), 5000); // 5s timeout
try {
const res = await fetch("/api/data", { signal });
clearTimeout(timer);
return res.json();
} catch (e) {
if (e.name === "AbortError") console.log("Request cancelled");
else throw e;
}
In React: call ctrl.abort() in the useEffect cleanup to cancel stale requests on unmount.
More in JavaScript