Own the lifecycle of a fetch request
Cancel obsolete work and ignore expected abort errors.
Give each request a controller
When a new query starts, abort the previous request and create a new AbortController. Pass its signal into fetch. Aborting asks participating APIs to stop work; still guard the state update because other asynchronous steps may not observe the signal. Keep the controller tied to the view's lifecycle.
Handle abort as a distinct outcome
An intentional abort during rapid typing is not a user-facing network failure. Detect it and skip the error display. Clear loading state only if the request still owns that state. On component cleanup, abort outstanding work so an unmounted view does not receive a late update.
const controller = new AbortController();
try {
const response = await fetch(url, { signal: controller.signal });
// Validate and render if this is still the current request.
} catch (error) {
if (error?.name !== 'AbortError') showError(error);
}
Test the race
Start request A, then B. Resolve B first and A later; B must remain visible. Repeat with A aborting and assert there is no false error. Clear the query while a request is pending and verify the page returns to a defined idle state.
Check your understanding
Why is aborting a prior fetch not the only stale-result safeguard?
Show explanation
Later async processing may still finish or ignore the signal. Check that the response still belongs to the current request before updating state.
You can read for free. Create an account to save your progress.
← Previous lesson: Design a resilient search flow Next lesson: Set a deadline and a safe retry policy →Put this lesson into practice
A practice activity at this level in the same module.
Try: Cancel outdated search requestsFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.