# Spot the bug - Search Results Race Condition

**URL:** <https://forum.kirupa.com/t/spot-the-bug-search-results-race-condition/684023>\
**Category:** Uncategorized\
**Created:** [November 14, 2026, 5:54am UTC](https://forum.kirupa.com/t/spot-the-bug-search-results-race-condition/684023 "2026-11-14T05:54:47Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Apexcodes](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/apexcodes/32/33967_2.png) [@Apexcodes](https://forum.kirupa.com/u/Apexcodes)\
**Post date:** [November 14, 2026, 5:54am UTC](https://forum.kirupa.com/t/spot-the-bug-search-results-race-condition/684023/1 "2026-11-14T05:54:47Z")

</div>

Why does this search sometimes display results for an older query?

```auto
let searchId = 0;

async function search(query) {
  const id = ++searchId;

  const response = await fetch(`/api/search?q=${query}`);
  const results = await response.json();

  document.querySelector("#results").textContent =
    results.map(item => item.name).join(", ");
}

```

Imagine a user types “JavaScript” and quickly changes it to “JavaScript tutorial”.

The second request finishes first, but the first request finishes later and overwrites the newer results.

**Your task:** Fix this so that only the latest search request can update the page.

Bonus: How would you handle errors and loading states?
