Part 11 / Topic 3 of 5
AbortController: cancel the request itself
AbortController is the real fix: instead of merely ignoring a stale response, it cancels the request that would have produced it. examples/03_abort_controller_cleanup.jsx's RestaurantSearchGuarded creates one controller per effect run, passes its signal to fetch, and aborts it from the cleanup function - which React calls right before this effect reruns for a new query, and once more on unmount:
// examples/03_abort_controller_cleanup.jsx
export function RestaurantSearchGuarded({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
const controller = new AbortController();
fetch(`/api/search?q=${query}`, { signal: controller.signal })
.then((res) => res.json())
.then((data) => setResults(data.results))
.catch((error) => {
if (error.name === "AbortError") return; // cancelled on purpose, not a real failure
throw error;
});
return () => controller.abort();
}, [query]);
return (
<ul aria-label="restaurant results">
{results.map((name) => <li key={name}>{name}</li>)}
</ul>
);
}
A cancelled fetch rejects its promise with an error named "AbortError" - this is a real, specified part of the Fetch API, not something this course invents - so the .catch here treats exactly that name as "nothing to do" and re-throws anything else, which would be a genuine failure worth surfacing. Running Section 2's identical scenario against this version (examples/03_abort_controller_cleanup.test.jsx) really aborts "pizza"'s request the instant "biryani" is typed - its promise is already rejected with AbortError by the time the test even tries to resolve it, so that attempt is a provable no-op (a settled promise cannot change), and the stale results never have a chance to appear. Unmounting a component with a request still in flight really aborts it too, with no unhandled error - the same cleanup function fires for both cases.
Done here? The practice set for Part 11 — including the solutions — is on the part page.