KatInterview

Fixing a Type-Ahead Search Box That Shows Stale Results

System DesignModel answer
MediumModel answerSystem Designreactrace-conditionabortcontroller

Last updated

Diagnose why a React search component sometimes displays results for an older query, then fix it with effect cleanup and request cancellation, and prove the fix with a deterministic test.

You own a small search box built in React. Each time the text in the input changes, the component calls a search endpoint and renders the returned list. Support tickets say the list on screen sometimes belongs to something the user typed a moment earlier, not to the text currently in the box. When you test the endpoint directly, every response is correct for the query that was sent, so the server is not at fault.

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>
  );
}

Requirements

  • The endpoint is correct per request; the defect is on the client.
  • Once typing stops, the screen must show the results for the final input. It must never switch to results for an earlier input. Leaving the old list visible while a new request is in flight is fine.
  • Use standard browser APIs and avoid adding unnecessary network traffic.

What to produce

  1. Describe how you would reproduce the problem reliably.
  2. Explain the root cause in terms of this component's code.
  3. Provide a corrected version, including how it treats errors caused by the fix itself.
  4. Point out any other defects in the snippet that affect what the user sees.
  5. Describe how you would verify the fix with an automated, deterministic test.

You may also discuss questions such as whether the backend could echo the query it answered, whether debouncing is acceptable, and whether the user should ever see an error for a request that is no longer needed.

Hints

Hint 1

Network responses do not have to arrive in the order the requests were sent. Ask what happens to the state when the response for an older query arrives after the response for a newer one.

Hint 2

An effect can return a cleanup function that runs before the next effect and on unmount. Think about what that cleanup could do to the request that is still in flight, and what kind of error cancelling produces.

Hint 3

Look beyond the race: what happens to a stale error message, to non-2xx responses, and to the empty-query branch that returns while a request is still pending?