Fetch, AbortController and race conditions: why search shows stale results
Prevent stale search results when overlapping browser requests complete out of order, using aborts and request versions.
A fast server can still return stale UI state
Suppose a user searches for 'Ank' and then 'Ankara'. Two HTTP requests may finish in the opposite order to which they started. If the older one resolves last, it can overwrite the newer results. This is a client-side race: both server responses may be valid while the visible interface is wrong. The same issue arises during rapid filter changes and pagination transitions.
AbortController can cancel an obsolete fetch
AbortController provides an AbortSignal that can cancel a pending fetch. When a new search starts, aborting the previous controller can avoid waiting for work no longer needed. However, a request might have reached the server already; aborting the browser operation does not guarantee rollback of a server-side write. Cancellation is not a transaction or data-integrity mechanism.
let currentController;
async function search(term) {
currentController?.abort();
currentController = new AbortController();
const response = await fetch('/api/search?q=' + encodeURIComponent(term), {
signal: currentController.signal
});
return response.json();
}Only the latest request should update the view
Cancellation alone does not eliminate every race. Other asynchronous steps may continue after the response has arrived, or promises might still resolve through a different path. Give every search an increasing request version and apply results only when that version matches the newest one. Treat AbortError as an expected cancellation instead of displaying it as a network failure.
Test realistic mobile interactions
Use throttled network responses to force the old request to finish after the new one. Test typing, deleting, blank queries, quick category changes, unmounting and offline transitions. The loading indicator should belong to the latest request; a stale request's finally handler must not hide the progress of a newer search.
Comments
0 real commentsNo real reader comments yet.
✎ Write a comment