Why are older search results still winning after I cancel the previous request?

MechaPrime
Wed, 08 Apr 2026 02:00:10 +0000

Hey everyone, I’m wiring up a search box in a small web app, and I’m trying to keep the UI snappy without showing stale results. I abort the previous fetch when a new query comes in, but under fast typing I still sometimes see an older response land last and replace the newer state, which makes the list flicker like a bad animation frame.

let controller;

async function runSearch(q) {
  if (controller) controller.abort();
  controller = new AbortController();

  const signal = controller.signal;
  const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, { signal });
  const data = await res.json();
  renderResults(data);
}

What is the cleanest way to guarantee only the latest request can update state without turning this into a tangled mess of ids and flags?

MechaPrime