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 q parameter.
  • 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

  1. Narrow down the symptom: right responses, wrong order

    Start from the two clues in the problem report:

    1. 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.
    2. 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 fetch on 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!

  2. Reproduce the race with a concrete timeline

    Before changing any code, make the timing mismatch visible:

    1. 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.
    2. 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) and console.log("received:", query) around fetch.

    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.

  3. 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 query changes, React runs this effect for the new query, while the promises for previous query values remain in flight and unconditionally call setResults whenever they finish. Looking carefully reveals four bugs in these ten lines:

    • Bug 1 — Stale responses overwrite fresh ones: An older, slower response calls setResults after 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, calls setResults([]), and returns — then q=ap finishes 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 triggers setError("Search failed").
    • Bug 4 — Unchecked HTTP 4xx/5xx responses: In browsers, fetch only rejects on network failures or cancellation, not on HTTP error codes like 500 Internal Server Error. Calling res.json() on a 500 error payload that has no results array calls setResults(undefined), crashing results.map(...) during render.
  4. Fix it with React effect cleanup and AbortController

    In React, a function returned from useEffect is a cleanup function: React calls it automatically right before running the effect for the next query (including when query becomes "") and when the component unmounts.

    Pair that cleanup with the standard browser AbortController API, which exposes a signal you pass into fetch and an abort() 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 / cancelled
    

    Here 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>
      );
    }
    
  5. Handle cancellation, HTTP status codes, and stale state cleanly

    Each guard inside the effect prevents a specific failure mode:

    • Ignore aborted requests in .catch(): Calling controller.abort() makes an in-flight fetch (or an in-progress res.json() body stream) reject with an AbortError. Without if (controller.signal.aborted) return;, typing quickly would flash "Search failed" on every single keystroke! Checking controller.signal.aborted is even safer than checking err.name === "AbortError", because calling controller.abort(customReason) rejects with customReason.
    • Check res.ok before res.json(): Turning 4xx/5xx HTTP statuses into thrown errors routes server errors cleanly into .catch() instead of letting results become undefined.
    • 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 call setResults([]) alongside setError("Search failed") so old results from an earlier query are not left displayed under the failed query; on !query we 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: Checking controller.signal.aborted before setResults costs one line and guarantees correctness even if a custom fetch wrapper or unit-test stub ignores signal.

    (Note: A simpler React-only pattern uses let ignore = false; inside useEffect and return () => { ignore = true; }; without AbortController. That also prevents stale setResults calls, but the browser keeps downloading obsolete response bodies over the network instead of cancelling them.)

  6. Confirm the fix with a deterministic automated test

    A test that sleeps for real timers (setTimeout(..., 500)) is slow and flaky. Instead, replace globalThis.fetch in the test with a controllable mock that stores a resolve callback per query q and listens to init?.signal's "abort" event just like a real browser fetch. 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).

  7. 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 same useEffect gives 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 and fetch is 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 useEffect cleanup: A useEffect cleanup function (the function returned from useEffect) runs right before the next effect execution and on unmount. Creating a fresh AbortController (a built-in browser object whose signal cancels a fetch when abort() is called) inside each effect run ties each request's lifetime to one query value.
  • Treat cancellation separately from real errors: Aborting rejects fetch or res.json() with an AbortError, so .catch() must return early when controller.signal.aborted is true. Real failures — including HTTP 4xx/5xx responses caught via if (!res.ok) throw ... — clear stale results and set "Search failed", while valid responses and empty inputs clear setError(null).
  • Verify with deterministic promise mocks: Mock fetch with 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: Calling controller.abort() causes the rejected promise to land in .catch(). Forgetting if (controller.signal.aborted) return; displays "Search failed" on almost every keystroke.
  • Reading a shared controllerRef.current inside .then() / .catch(): If an old request's callback checks controllerRef.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 local const 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() after if (!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): fetch resolves normally on HTTP 500 or 404, so parsing an error body without data.results sets results to undefined and crashes results.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" at t = 0 and pauses, firing q=app at t = 300 ms; then they type "le" at t = 350 ms and pause, firing q=apple at t = 650 ms. If q=app is slow (900 ms, arriving at t = 1200 ms) and q=apple is fast (200 ms, arriving at t = 850 ms), q=app still 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 fetch with a mock that stores a manual resolve function per query string in a Map and rejects with new DOMException("Aborted", "AbortError") when init.signal fires "abort". Render the component, trigger input changes for "app" and then "apple", manually resolve "apple" first and "app" second inside act(...), 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 as req.on("close") in Node.js or r.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 by query.
  • How would you implement the equivalent request-cancellation logic in vanilla TypeScript using a class attached to an element? Store private controller: AbortController | null = null as an instance field on the class, call this.controller?.abort() at the very top of search(query) (even before checking if (!query) so clearing the box cancels in-flight requests!), and capture a local const controller = new AbortController() for the new request so callbacks check their own controller.signal.aborted. Using li.textContent = r.name also 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 with switchMap + 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

Similar questions

More Tradedesk interview questions

All 5 Tradedesk questions →