Fetch basics
The fetch function returns a promise that resolves to a Response. A key gotcha is that fetch only rejects on network failure, not on HTTP error status.
- A 404 or 500 still resolves successfully.
- You must check response ok or the status yourself and throw if needed.
- Call response json or response text to read the body, which returns another promise.
Cancelling with AbortController
An in flight request can be cancelled with an AbortController. You create a controller, pass its signal to fetch, and call abort to cancel.
- Aborting rejects the fetch promise with an abort error you can catch and ignore.
- This matters for search as you type, where each keystroke should cancel the previous request.
- It also prevents setting state after a component unmounts.
A common pattern is to store the controller, abort it before starting a new request, and create a fresh one each time.
Key idea
Fetch resolves even on 404 so check response ok, and pass an AbortController signal to cancel stale requests like rapid search queries.