πŸ”΄ HardAsync BugsπŸ› Debug Challenge

Race condition in state update

Buggy Code β€” Can you spot the issue?

async function handleSearch(query) {
  setLoading(true);
  const results = await searchAPI(query);
  setResults(results);
  setLoading(false);
}

input.addEventListener('input', (e) => {
  handleSearch(e.target.value);
});

Fixed Code

let currentQuery = '';

async function handleSearch(query) {
  currentQuery = query;
  setLoading(true);

  const results = await searchAPI(query);

  // Discard stale results
  if (query !== currentQuery) return;

  setResults(results);
  setLoading(false);
}

// Better: also debounce the input
const debouncedSearch = debounce(handleSearch, 300);
input.addEventListener('input', (e) => {
  debouncedSearch(e.target.value);
});

Bug Explained

Bug: If user types "react" quickly, 5 requests fire. Whichever resolves LAST wins β€” could be an earlier query returning stale results.

Explanation: Track the latest query. When a response arrives, check if it's still the current query. If not, discard it. Also use debounce to reduce requests.

Key Insight: Race conditions in search: always validate that the response matches the latest request. AbortController is the modern approach.

More Async Bugs Debug Challenges

🟒 EasyMissing await causes wrong resultβ†’πŸŸ‘ MediumSequential awaits killing performanceβ†’πŸŸ‘ MediumSwallowed error in async functionβ†’πŸ”΄ HardAsync function in forEachβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab