Spot the bug - Search Results Race Condition

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

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?