Digiaru

Digiaru started this conversation 1 week ago.

Race condition in async fetch: stale autocomplete results override current data

Implementing autocomplete: users type fast, sending multiple fetch calls. Sometimes, results from an earlier request replace the newer ones, causing wrong suggestions to display.

Kar

Posted 1 week ago

Fetch requests return in unpredictable order, causing race conditions—newer UI state can be overwritten by outdated responses ([turn0search11]). Fixes: • Track request IDs and ignore stale responses: js Copy code let latest = 0; async function search(q){ const id = ++latest; const res = await fetch(/search?q=${q}); if (id !== latest) return; // ignore show(res); } • Or use AbortController to cancel outdated requests: js Copy code controller.abort(); fetch(url, { signal: controller.signal });