Debugging Out-of-Order Fetch Results in React
Medium · Software Engineering Fundamentals · Frontend Engineer · Onsite
Prompt
A live-search React component fires an HTTP request each time the user edits a text input and renders the returned items. In production, users occasionally end up seeing matches from an earlier keystroke instead of the string currently inside the input box—for instance, typing "ap", "app", and "apple" briskly can briefly show matches for "apple" before reverting to items for "ap" or "app". Inspecting any individual backend call confirms the endpoint always returns accurate JSON for its own q query parameter.
Diagnose the client-side bug(s) in the representative component below, rewrite the effect to eliminate them, and explain how to verify the fix deterministically with an automated test.
import { useEffect, useState } from "react";
type Result = { id: string; name: string };
export function SearchResults() {
const [query, setQuery] = useState("");
const [results, setResults] = useState<Result[]>([]);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!query) {
setResults([]);
return;
}
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then(res => res.json())
.then(data => setResults(data.results))
.catch(() => setError("Search failed"));
}, [query]);
return (
<div>
<input value={query} onChange={e => setQuery(e.target.value)} />
{error && <p>{error}</p>}
<ul>
{results.map(r => (
<li key={r.id}>{r.name}</li>
))}
</ul>
</div>
);
}
Keep the following requirements in mind:
- Assume the server endpoint cannot be modified and always responds accurately for its
qparameter. - Once typing stops, the rendered list must settle on the matches for the final input value (or become empty when the input is cleared) and must never be overwritten by an earlier request; keeping prior items visible while the newest request loads is acceptable.
- Rely only on standard browser and React APIs without adding extra network traffic, and ensure cancelled or superseded requests never surface error banners.
Scope & Expectations
- Explain how variable network and database latencies create an out-of-order response race condition across rapid keystrokes, including empty-input and error-banner edge cases.
- Use React effect cleanup with
AbortController(alongside proper HTTP status checks and abort guards) so superseded requests cannot overwrite current UI state. - Show how to reproduce the failure mode and verify the fix deterministically in a fast unit test using controlled promises rather than wall-clock timers.
Step-by-step walkthrough
Narrow down the symptom: right responses, wrong order
Start from the two clues in the problem report:
- Every individual API request, inspected on its own, returns the exact right JSON for its query parameter
q. That rules out server-side search bugs, bad URL encoding, or broken JSON parsing. - What ends up on screen sometimes belongs to an earlier keystroke rather than the text currently inside the
<input>.
Whenever individually accurate operations combine into the wrong final state depending on how fast they finish, suspect a race condition — a bug where program behavior depends on the unpredictable timing of overlapping asynchronous work. Here, the component fires a new
fetchon every keystroke, and network responses are not guaranteed to return in the order they were sent. In fact, broader prefixes like"ap"or"app"usually scan far more database rows than a specific query like"apple", making older requests slower than newer ones right when users are typing!- Every individual API request, inspected on its own, returns the exact right JSON for its query parameter
Reproduce the race with a concrete timeline
Before changing any code, make the timing mismatch visible:
- Open browser DevTools -> Network tab, enable network throttling (such as Slow 3G), and type
"apple"briskly. Compare the request Start Time order against the response End Time order in the Waterfall chart. - Because uniform browser throttling adds roughly constant latency to every request, responses can still arrive in order. To reproduce the bug reliably on demand, add a random server delay (or delay shorter queries longer in a local mock) or log
console.log("sent:", query)andconsole.log("received:", query)aroundfetch.
Here is a concrete three-update timeline that triggers the bug:
Time Event Input box Displayed list ------ --------------------------------------- --------- ---------------------------- 0 ms User types "ap" -> Request 1 (q=ap) "ap" [] 120 ms User types "app" -> Request 2 (q=app) "app" [] 240 ms User types "apple" -> Request 3 (q=apple) "apple" [] 500 ms Response 3 (q=apple) arrives first "apple" ["Apple cider"] (correct) 650 ms Response 1 (q=ap) arrives late "apple" ["Apricot jam"] (WRONG!) 700 ms Response 2 (q=app) arrives last "apple" ["Appetizer tray"] (WRONG!)When typing stops, the input says
"apple", yet the list stays stuck on"Appetizer tray". The last response to arrive wins, when the last request sent should win.- Open browser DevTools -> Network tab, enable network throttling (such as Slow 3G), and type
Inspect the buggy effect and its hidden sibling bugs
Look closely at the component's
useEffect:useEffect(() => { if (!query) { setResults([]); return; } fetch(`/api/search?q=${encodeURIComponent(query)}`) .then(res => res.json()) .then(data => setResults(data.results)) // runs for EVERY request ever started! .catch(() => setError("Search failed")); }, [query]); // missing cleanup function!Every time
querychanges, React runs this effect for the newquery, while the promises for previousqueryvalues remain in flight and unconditionally callsetResultswhenever they finish. Looking carefully reveals four bugs in these ten lines:- Bug 1 — Stale responses overwrite fresh ones: An older, slower response calls
setResultsafter a newer response has already rendered. - Bug 2 — Ghost results under an empty input: Type
"ap"and immediately clear the box. The new effect sees!query, callssetResults([]), and returns — thenq=apfinishes 300 ms later and populates search results underneath a blank input box! - Bug 3 — Stale and sticky errors:
setError(null)is never called, so one transient error banner stays stuck on screen forever even after later searches succeed. Worse, an obsolete request that fails after the latest request succeeded still triggerssetError("Search failed"). - Bug 4 — Unchecked HTTP 4xx/5xx responses: In browsers,
fetchonly rejects on network failures or cancellation, not on HTTP error codes like500 Internal Server Error. Callingres.json()on a500error payload that has noresultsarray callssetResults(undefined), crashingresults.map(...)during render.
- Bug 1 — Stale responses overwrite fresh ones: An older, slower response calls
Fix it with React effect cleanup and AbortController
In React, a function returned from
useEffectis a cleanup function: React calls it automatically right before running the effect for the nextquery(including whenquerybecomes"") and when the component unmounts.Pair that cleanup with the standard browser
AbortControllerAPI, which exposes asignalyou pass intofetchand anabort()method that cancels the request immediately:Time Event Active request Older requests ------ --------------------------------------- ------------------ ------------------------ 0 ms query = "ap" -> Effect 1 starts controller1 (none) 120 ms query = "app" -> Cleanup 1 runs controller2 controller1.abort()! 240 ms query = "apple" -> Cleanup 2 runs controller3 controller2.abort()! 500 ms Response 3 (q=apple) resolves sets ["Apple cider"] ignored / cancelledHere is the fixed component:
import { useEffect, useState } from "react"; type Result = { id: string; name: string }; export function SearchResults() { const [query, setQuery] = useState(""); const [results, setResults] = useState<Result[]>([]); const [error, setError] = useState<string | null>(null); useEffect(() => { if (!query) { setResults([]); setError(null); return; } const controller = new AbortController(); fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal }) .then(res => { if (!res.ok) { throw new Error(`HTTP ${res.status}`); } return res.json(); }) .then(data => { if (controller.signal.aborted) return; // superseded by a newer query setResults(data.results); setError(null); }) .catch(() => { if (controller.signal.aborted) return; // intentional cancellation, not an error setResults([]); setError("Search failed"); }); return () => controller.abort(); }, [query]); return ( <div> <input value={query} onChange={e => setQuery(e.target.value)} /> {error && <p>{error}</p>} <ul> {results.map(r => ( <li key={r.id}>{r.name}</li> ))} </ul> </div> ); }Handle cancellation, HTTP status codes, and stale state cleanly
Each guard inside the effect prevents a specific failure mode:
- Ignore aborted requests in
.catch(): Callingcontroller.abort()makes an in-flightfetch(or an in-progressres.json()body stream) reject with anAbortError. Withoutif (controller.signal.aborted) return;, typing quickly would flash"Search failed"on every single keystroke! Checkingcontroller.signal.abortedis even safer than checkingerr.name === "AbortError", because callingcontroller.abort(customReason)rejects withcustomReason. - Check
res.okbeforeres.json(): Turning 4xx/5xx HTTP statuses into thrown errors routes server errors cleanly into.catch()instead of lettingresultsbecomeundefined. - Clear stale state on transitions: On success we call
setError(null)so past error banners disappear; on a genuine failure of the current query we callsetResults([])alongsidesetError("Search failed")so old results from an earlier query are not left displayed under the failed query; on!querywe clear both. While a new valid request is still loading, previous results remain visible cleanly until the new response or error lands. - Guard
.then()as well: Checkingcontroller.signal.abortedbeforesetResultscosts one line and guarantees correctness even if a customfetchwrapper or unit-test stub ignoressignal.
(Note: A simpler React-only pattern uses
let ignore = false;insideuseEffectandreturn () => { ignore = true; };withoutAbortController. That also prevents stalesetResultscalls, but the browser keeps downloading obsolete response bodies over the network instead of cancelling them.)- Ignore aborted requests in
Confirm the fix with a deterministic automated test
A test that sleeps for real timers (
setTimeout(..., 500)) is slow and flaky. Instead, replaceglobalThis.fetchin the test with a controllable mock that stores aresolvecallback per queryqand listens toinit?.signal's"abort"event just like a real browserfetch. Then drive the race in the exact failing order — resolve"apple"first and"app"second:import { act, fireEvent, render, screen } from "@testing-library/react"; import { SearchResults } from "./SearchResults"; type Result = { id: string; name: string }; function createControlledFetch() { const resolvers = new Map<string, (results: Result[]) => void>(); const fetchMock = jest.fn((url: string, init?: RequestInit) => new Promise<Response>((resolve, reject) => { const q = new URL(url, "http://localhost").searchParams.get("q") ?? ""; if (init?.signal?.aborted) { reject(new DOMException("Aborted", "AbortError")); return; } init?.signal?.addEventListener( "abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true }, ); resolvers.set(q, results => resolve({ ok: true, status: 200, json: async () => ({ results }), } as Response), ); }), ); globalThis.fetch = fetchMock as unknown as typeof fetch; return { fetchMock, resolvers }; } async function resolveQuery( resolvers: Map<string, (r: Result[]) => void>, q: string, results: Result[], ) { await act(async () => { resolvers.get(q)!(results); await new Promise(r => setTimeout(r, 0)); // flush promise microtasks }); } describe("SearchResults", () => { const originalFetch = globalThis.fetch; afterEach(() => { globalThis.fetch = originalFetch; }); test("a late response for an older query never overwrites newer results", async () => { const { fetchMock, resolvers } = createControlledFetch(); render(<SearchResults />); const input = screen.getByRole("textbox"); fireEvent.change(input, { target: { value: "app" } }); fireEvent.change(input, { target: { value: "apple" } }); // Newer request finishes FIRST; older request tries to finish SECOND. await resolveQuery(resolvers, "apple", [{ id: "1", name: "Apple cider" }]); await resolveQuery(resolvers, "app", [{ id: "2", name: "Appetizer tray" }]); expect(screen.getByText("Apple cider")).toBeInTheDocument(); expect(screen.queryByText("Appetizer tray")).not.toBeInTheDocument(); expect(screen.queryByText("Search failed")).not.toBeInTheDocument(); expect(fetchMock).toHaveBeenCalledTimes(2); }); });Run this test against the original buggy component first: it deterministically fails because
"Appetizer tray"replaces"Apple cider". Against the fixed component, typing"apple"aborts"app","Search failed"stays hidden, and"Apple cider"stays on screen. Add companion tests using the same helper for: 1. Typing"ap", clearing the input to"", then resolving"ap"(list must stay empty). 2. Rejecting an older aborted query after the newest query succeeded (no error message shown). 3. Returning{ ok: false, status: 500 }for the active query ("Search failed"appears and stale items clear).Optional enhancement: combine cancellation with debouncing
Debouncing means waiting for a brief pause in typing (say
250 ms) before sending a network request. Debouncing is a traffic optimization, not a correctness fix on its own (two requests sent after two separate pauses can still return out of order!). Combining both inside the sameuseEffectgives zero wasted keystroke requests and zero stale-response bugs:useEffect(() => { if (!query) { setResults([]); setError(null); return; } const controller = new AbortController(); const timerId = setTimeout(() => { fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal }) .then(res => { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); }) .then(data => { if (controller.signal.aborted) return; setResults(data.results); setError(null); }) .catch(() => { if (controller.signal.aborted) return; setResults([]); setError("Search failed"); }); }, 250); return () => { clearTimeout(timerId); controller.abort(); }; }, [query]);If the user types another character within 250 ms,
clearTimeout(timerId)cancels the scheduled fetch before it even hits the network; if 250 ms already elapsed andfetchis in flight,controller.abort()cancels the HTTP request.
Intuition & how it works
Imagine asking an office assistant to fetch a folder labeled "App", changing your mind a split second later and asking a second assistant to fetch "Apple", and having the "Apple" assistant sprint back first while the slower "App" assistant strolls back ten seconds later and drops the "App" folder right on top of your desk. Both assistants fetched the exact folder they were asked for, yet you end up staring at the wrong folder because nobody told the first assistant "never mind!" when your request changed.
Firing fetch inside useEffect without cleanup makes that exact mistake: every keystroke launches an independent asynchronous request whose .then(...) callback unconditionally overwrites results whenever it arrives. Because network latency and database query cost vary per request (broad prefixes like "ap" often scan far more rows than "apple"), responses routinely return out of order, letting the last response to arrive overwrite the last request sent.
Trace typing "app" at t = 0 ms and "apple" at t = 100 ms, where "apple" takes 150 ms and "app" takes 500 ms:
1. Without cleanup (buggy): "apple" arrives at t = 250 ms and renders ["Apple cider"]; "app" arrives late at t = 600 ms and overwrites the list with ["Appetizer tray"] even though the input says "apple".
2. With AbortController in useEffect cleanup (fixed): At t = 100 ms, changing query from "app" to "apple" runs the first effect's cleanup function (controller1.abort()), immediately cancelling "app". Its AbortError is ignored in .catch(), and "apple" arrives at t = 250 ms to render ["Apple cider"] permanently.
Key points
- Race condition root cause: A race condition occurs when correctness depends on which overlapping asynchronous task finishes first. Without cancellation, out-of-order HTTP responses overwrite newer UI state, including populating results under an input box the user just cleared to
"". - Reproduce by comparing send vs. arrival order: Use DevTools Network throttling or a mock server with per-query delays to observe an earlier request finishing after a later one in the Waterfall timeline.
- Cancel in React's
useEffectcleanup: AuseEffectcleanup function (the function returned fromuseEffect) runs right before the next effect execution and on unmount. Creating a freshAbortController(a built-in browser object whosesignalcancels afetchwhenabort()is called) inside each effect run ties each request's lifetime to onequeryvalue. - Treat cancellation separately from real errors: Aborting rejects
fetchorres.json()with anAbortError, so.catch()must return early whencontroller.signal.abortedistrue. Real failures — including HTTP 4xx/5xx responses caught viaif (!res.ok) throw ...— clear stale results and set"Search failed", while valid responses and empty inputs clearsetError(null). - Verify with deterministic promise mocks: Mock
fetchwith test-controlled promises resolved out of order (newest first, oldest second), verify the test fails on the original code, and verify it passes on the fixed code.
Common mistakes
- Blaming backend bugs or HTTP caching: Every individual response is accurate for its own query parameter; the bug is purely client-side state ordering.
- Thinking debouncing fixes the race: Debouncing (delaying a search until typing pauses) lowers request volume, which makes the race less frequent in manual testing while leaving it broken in production whenever two paused searches overlap in flight.
- Aborting without ignoring
AbortError: Callingcontroller.abort()causes the rejected promise to land in.catch(). Forgettingif (controller.signal.aborted) return;displays"Search failed"on almost every keystroke. - Reading a shared
controllerRef.currentinside.then()/.catch(): If an old request's callback checkscontrollerRef.current.signal.aborted, it inspects the newest request's controller (which is not aborted!) instead of its own, letting stale responses slip through. Capturing a localconst controller = new AbortController()inside the closure binds each callback to its own request. - Skipping cancellation when the input is cleared: In imperative code (outside React's cleanup lifecycle), placing
controller.abort()afterif (!query) return;leaves the previous request alive when the user clears the search box, causing ghost results to appear under an empty input. - Forgetting
if (!res.ok):fetchresolves normally on HTTP500or404, so parsing an error body withoutdata.resultssetsresultstoundefinedand crashesresults.map(...).
Follow-up questions
- Does debouncing the text input eliminate this stale-state bug by itself? Explain why or why not. No — debouncing only reduces how often requests are sent, not whether two sent requests can overlap on the wire. Suppose you debounce by
300 ms: the user types"app"att = 0and pauses, firingq=appatt = 300 ms; then they type"le"att = 350 msand pause, firingq=appleatt = 650 ms. Ifq=appis slow (900 ms, arriving att = 1200 ms) andq=appleis fast (200 ms, arriving att = 850 ms),q=appstill arrives last and overwrites"apple"unless you also cancel or ignore superseded requests. - How can you test out-of-order response handling in CI without setTimeout sleeps or flaky network delays? Replace
fetchwith a mock that stores a manualresolvefunction per query string in aMapand rejects withnew DOMException("Aborted", "AbortError")wheninit.signalfires"abort". Render the component, trigger input changes for"app"and then"apple", manually resolve"apple"first and"app"second insideact(...), and assert that"Apple cider"is rendered,"Appetizer tray"is absent, and"Search failed"is absent. Because promise resolution order is scripted rather than timer-driven, the test runs in milliseconds with zero flakiness, fails every time on the buggy code, and passes every time with the fix. - Does aborting fetch in the browser actually save backend CPU and database work, or only protect UI state? Mostly it protects client state and saves client download bandwidth rather than saving server CPU. Because the component still sends a request on every keystroke, the HTTP request has usually already reached the server before
controller.abort()fires on the next keystroke; over HTTP/2 the browser cancels that stream (RST_STREAM), whereas over HTTP/1.1 it may have to close the TCP socket to stop receiving the body. The server only saves database or compute work if its handler explicitly listens for client disconnect signals (such asreq.on("close")in Node.js orr.Context().Done()in Go) and propagates cancellation downstream; to actually send fewer requests to the server, add debouncing, a minimum query length, or a client-side result cache keyed byquery. - How would you implement the equivalent request-cancellation logic in vanilla TypeScript using a class attached to an element? Store
private controller: AbortController | null = nullas an instance field on the class, callthis.controller?.abort()at the very top ofsearch(query)(even before checkingif (!query)so clearing the box cancels in-flight requests!), and capture a localconst controller = new AbortController()for the new request so callbacks check their owncontroller.signal.aborted. Usingli.textContent = r.namealso prevents cross-site scripting (XSS) if result names contain<script>characters. (In reactive libraries like RxJS, the exact same "cancel previous inner request when a new input arrives" pattern is expressed declaratively withswitchMap+fromFetch.)
type Result = { id: string; name: string };
class SearchBox {
private controller: AbortController | null = null;
constructor(
private input: HTMLInputElement,
private list: HTMLUListElement,
private errorBox: HTMLElement,
) {
input.addEventListener("input", () => {
void this.search(input.value);
});
}
private async search(query: string): Promise<void> {
// Always cancel any previous in-flight request first, even when clearing to "".
this.controller?.abort();
this.controller = null;
if (!query) {
this.renderResults([]);
return;
}
const controller = new AbortController();
this.controller = controller;
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (controller.signal.aborted) return;
this.renderResults(data.results);
} catch {
if (controller.signal.aborted) return;
this.list.replaceChildren();
this.errorBox.textContent = "Search failed";
}
}
private renderResults(results: Result[]): void {
this.errorBox.textContent = "";
const items = results.map(r => {
const li = document.createElement("li");
li.textContent = r.name;
return li;
});
this.list.replaceChildren(...items);
}
}
Follow-up questions
- Does debouncing the text input eliminate this stale-state bug by itself? Explain why or why not.
- How can you test out-of-order response handling in CI without setTimeout sleeps or flaky network delays?
- Does aborting fetch in the browser actually save backend CPU and database work, or only protect UI state?
- How would you implement the equivalent request-cancellation logic in vanilla TypeScript using a class attached to an <input> element?
Similar questions
- Resilient Caching Client for Daily Equity Prices
- In-Memory Publish-Subscribe Event Bus
- Multi-Car Elevator Dispatch Simulator
- Two-Level In-Memory Store with Field Expiration
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target