How do I cancel an outdated fetch when a newer search begins?
Quick answer
Create an AbortController for each search and pass its signal to fetch. When a new search starts, abort the previous controller and create a new one. Treat an AbortError as an expected cancellation, not a search failure. Before displaying results, also check that the response still belongs to the current search; this prevents outdated results from replacing newer ones.
The question, the details, the next step.
A practical checklist
Store the active AbortController where each search can access it.
Abort the previous controller before starting a replacement search.
Pass the new controller’s signal in the fetch options.
Return quietly for AbortError; handle other failures separately.
Check that the request is still current immediately before updating the UI.
A few more useful answers
What signal does fetch need for cancellation?
Pass the controller’s signal in the request options, as { signal: controller.signal }. Calling that controller’s abort() method cancels the associated operation. [S1]
Can reading the response body also be aborted?
Yes. The cited guide notes that body reading can reject with AbortError if the request is aborted after response headers arrive. Handle that as an expected cancellation too. [S1]
Does this example define how my search API responds?
No. The endpoint and UI functions are placeholders. Adapt the request and response handling to your own API and keep the current-request check before rendering.
Sources
References used for this guide.
- [S1] Using the Fetch API — Web APIs | MDN developer.mozilla.org · Checked
