An older response overwrites a newer one — how do you prevent it?
Answer out loud or in your head first, then compare.
Answer
When the query changes, I cancel the previous work and ignore its late result. A debounce on its own limits frequency, but doesn't fix the order of responses.
JSX
useEffect(() => {
const controller = new AbortController();
let ignore = false;
setLoading(true);
setError(null);
fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
}).then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
}).then(data => { if (!ignore) setResults(data); })
.catch(error => {
if (!ignore && error.name !== 'AbortError') setError(error);
}).finally(() => { if (!ignore) setLoading(false); });
return () => { ignore = true; controller.abort(); };
}, [query]);To be precise: the snippet assumes the state setters exist. If the API doesn't support cancellation, the protection against a stale result still holds.
How did it go? Be honest — “Not yet” puts the question on your review list.
Related questions
- C02 · How do you avoid showing the response to an older search? — React, Next.js and frontend
Practise in code
- A search that shows a stale result — runs tests in your browser