Data Fetching
Model loading, error, empty, and success states without stale request races.
Production frameworks often provide route-level loading and caching. When fetching in a client component, handle cancellation and every visible state.
Fetch with cleanup
Lessons.tsx
useEffect(() => {
const controller = new AbortController();
setStatus("loading");
fetch(`/api/courses/${course}`, { signal: controller.signal })
.then((response) => { if (!response.ok) throw new Error(String(response.status)); return response.json(); })
.then((data) => { setLessons(data); setStatus("ready"); })
.catch((error) => { if (error.name !== "AbortError") setStatus("error"); });
return () => controller.abort();
}, [course]);
Cancellation prevents a stale request from updating a newer screen. Validate the response before saving it.
Prefer a data layer at scale
A framework loader or query library can handle caching, deduplication, revalidation, retries, and server rendering more consistently than repeated component effects.
Keep this
Represent every state, cancel stale work, validate data, and use framework-level fetching when the application needs shared caching.
学习位置已保存在此设备上。