Skip to content

QuizNot attempted

Spot the bug: fast filter changes

The user picks "Storage" then quickly "Compute", and the Storage response arrives last. What is shown, and what is the fix?
useEffect(() => {
if (selectedValue === '') return;
const fetchFilteredData = async () => {
const res = await fetch(`/api/resources/${selectedValue}`);
setResourceData(await res.json());
};
fetchFilteredData();
}, [selectedValue]);
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Storage rows under the Compute filter; abort the request (or set an ignore flag) in the effect cleanup

Nothing cancels the old request, so whichever response lands LAST wins. Cancel it in cleanup:

useEffect(() => {
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then((r) => r.json())
.then(setRows)
.catch((e) => { if (e.name !== 'AbortError') setError(e); });
return () => controller.abort();
}, [selectedValue]);

An ignore flag set to true in cleanup also works (it drops the response but doesn't cancel the network call). A query library keyed by the filter does this for you. Not most recent state: the late response's setState IS the most recent update. Not the dependency array: selectedValue is already there. Not request order: separate HTTP requests can finish in any order.