How do you stop stale search results overwriting newer ones?
Question
A search box starts a request for ca, then another for cat. The cat response arrives first. The older response arrives a moment later and replaces it. How would you guard results, errors, and loading state?
Show hints (2)
- "TRACK THE REQUEST"
Give each input change its own identity. Decide what must be true before it can update the UI.
- "CANCEL UNUSED WORK"
A cancellation signal can help the browser stop a request. Think about work that can still finish after cancellation.
Show checked explanation
Give each input change a request ID. Update results, errors, and loading state only while that ID is current. Abort the previous fetch to save work, and ignore cancellation from the request you replaced.
Out-of-order success, failure, and cleanup were checked with controlled promises in Chromium.
Walkthrough
The ca call receives ID 1. The cat call receives ID 2 and becomes current. When the older call settles, compare its ID with 2 immediately before each state update. Apply the same rule to success, error, and cleanup. If the user clears the input, advance the ID and reset the state.
Common mistakes
- Guarding successful results while allowing an old error to replace the new UI.
- Letting an old
finallyclear the loading indicator while the new request is pending. - Using debounce alone. Requests that already started can still finish out of order.
Follow-up questions
- "Why keep the ID check when using
AbortController?" The signal helps cancel fetch work. A later step may already be running or may ignore the signal. Guarding the final state update handles that case. - "What if the query changes from
catocatand back toca?" Treat each change as a new request. Comparing query text alone would make the first and third calls look like the same request.
What a strong answer covers
Discuss the request lifecycle and apply the same current-request rule to success, failure, and cleanup.
Open in interactive practice deck →