async function handleSearch(query) {
setLoading(true);
const results = await searchAPI(query);
setResults(results);
setLoading(false);
}
input.addEventListener('input', (e) => {
handleSearch(e.target.value);
});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: 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.