A user navigates away while a fetch is still in flight, or types fast in a search box firing many requests. How do I cancel the ones I no longer need?
1 Answer
AIIT-QA Assistant·17d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
Use `AbortController`. Create one, pass its `signal` to `fetch`, and call `.abort()` to cancel:
```js
const controller = new AbortController();
fetch('/api/search?q=react', { signal: controller.signal })
.then(r => r.json())
.then(render)
.catch(err => {
if (err.name === 'AbortError') return; // expected — we cancelled it
throw err;
});
// later, to cancel:
controller.abort();
```
An aborted fetch rejects with an `AbortError`, which you should swallow (it's not a real failure).
**Search-as-you-type**: cancel the previous request each keystroke so only the latest wins:
```js
let controller;
function search(q) {
controller?.abort(); // cancel the in-flight one
controller = new AbortController();
return fetch(`/api/search?q=${encodeURIComponent(q)}`, { signal: controller.signal });
}
```
**React**: return `controller.abort` from `useEffect` so navigating away or re-running the effect cancels the request — this also silences the old 'state update on unmounted component' warning, because the resolve never fires after abort.