- Published on
- 2 min read
Make search results belong to the latest query
- Authors
- Name
- Ritenta
A person types “ca”, then “cat”. The “cat” request finishes first; a slow “ca” response arrives later and replaces the better result. This is a race between requests, not a sorting bug. A search UI needs an ownership rule: only the latest query may update the results.
Cancel work and guard the update
AbortController sends a cancellation signal to fetch(). It avoids spending resources on a request the UI no longer wants. A separate request number protects the display even when cancellation arrives too late, a server has already responded, or other asynchronous work continues. MDN documents AbortController.
let currentController;
let latestRequest = 0;
async function search(query) {
currentController?.abort();
const controller = new AbortController();
currentController = controller;
const requestId = ++latestRequest;
try {
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
if (!response.ok) throw new Error(`Search failed: ${response.status}`);
const results = await response.json();
if (requestId === latestRequest && !controller.signal.aborted) {
showResults(results);
}
} catch (error) {
if (controller.signal.aborted) return;
if (requestId === latestRequest) showError(error);
}
}
showResults and showError stand for your UI update functions. In a React effect, perform the same cleanup when the query changes or the component unmounts. React's effect guide explains cleanup between runs. A query library may already manage cancellation and stale results; know its contract before adding a second mechanism.
Check the visible states
Throttle the network and type several queries quickly. The loading indicator and error must also belong to the latest query; an old failure should not erase newer success. Empty input should clear or reset the results according to the product rule. Test with a request that completes just before cancellation as well as one that finishes afterward. A fast local connection rarely exposes this bug without deliberate throttling.