Handle stale async results
Keep loading, success and error states coherent when requests overlap.
Requests can finish out of order
A user can search for A, then B, while A is still loading. If A finishes last and blindly updates the view, the page shows the wrong result. Cancel obsolete requests with AbortController or compare a request sequence before updating state.
Model all outcomes
Represent loading, data, empty and error states explicitly. Clear stale errors when starting a new request. Never leave the interface indefinitely loading after a rejection; use try/catch/finally, while making sure an older request cannot clear a newer request's loading state.
const current = ++requestId;
try {
const rows = await load(query);
if (current === requestId) render(rows);
} catch (error) {
if (current === requestId) showError(error);
}
Follow a two-query timeline
Imagine query A starts, then query B starts. B resolves first and renders. A resolves later. Without a guard, A replaces B's result even though the input still shows B. Track the latest request ID or abort A when B starts. Also ignore an aborted request's error so it does not flash a false failure to the user.
Keep state transitions explicit
A request can be loading, successful with rows, successful but empty, or failed. Define what should happen to the old rows during loading and error. A search UI may keep old rows with a 'refreshing' cue; a payment confirmation should not. Test the chosen transition for overlapping requests and unmounting, not only the happy path.
Check your understanding
Why can an earlier search response overwrite a later one?
Show explanation
Network completion order is independent of request order. Cancel or ignore responses that no longer represent the current query.
You can read for free. Create an account to save your progress.
← Previous lesson: Build a keyboard-usable control Next lesson: Handle partial success across requests →Try it at foundation level
Write a tiny search-state reducer. Fire request A, then B, and resolve A last; show the state after each event.
Check your work
The late A response cannot replace B, and loading, empty, success, and error states are distinguishable.
Self-guided practice. This does not record assessed mastery.
Put this lesson into practice
A related activity in this module at mid level.
Try: Cancel outdated search requestsFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.