Part 11 / Stage 3
Fetching data
Goal: Fetch data inside
useEffectwithout the three mistakes that quietly break almost every first attempt - modeling loading/error/success as three disagreeing booleans instead of one value, letting a slower earlier request overwrite a faster later one, and leaking a request that nobody is waiting for anymore - then cancel a stale request for real withAbortController, stop coding independent requests one after another, and move the whole pattern into a reusable hook. Time: ~5 hours · Level: comfortable withuseEffectand cleanup (Part 6), and writing a custom hook (Part 7)
What you will learn
- Why three independent booleans (
isLoading/isError/data) are a worse model for "where is this fetch right now?" than one value that can only ever be exactly one of three shapes - "boolean soup," proven with a real bug, not just asserted - The race condition at the heart of fetching-in-an-effect: an earlier request that resolves after a later one silently overwrites it, reproduced for real with two requests whose resolution order you control
AbortController: passing asignaltofetch, cancelling it from an effect's cleanup function, and treating the resultingAbortErroras "nothing to do," not a real failure - the fix for the race above, not a separate topic from it- Avoiding waterfalls: two independent requests coded one after another (each waiting for the previous to finish) cost as long as both together, for no reason -
Promise.allstarts both in the same tick instead - Where fetching logic belongs: extracting a
useFetch(url)custom hook (Part 7) that packages loading/error/success modeling andAbortControllercleanup once, so no component that needs data has to re-derive either - This part's running examples: an order-status loader, a restaurant search box, an IRCTC-style trip dashboard, and a reusable
useFetchhook used by two independent restaurant widgets - No real network call anywhere in this part. Every test stubs
fetchitself (vi.stubGlobal("fetch", ...)or a hand-rolled fakeResponse), so every result below is offline and exactly repeatable - not "usually works," not dependent on a real API staying up
A note on how this part is organised: same convention as Parts 1-7 - every
examples/andsolutions/file here is wired into this repo's ownharness/and actually executed before being shown below. When you build along, type the code into your own project; this repo's copy is the verified reference, not something you need to open.
Topics in this part
Practice
Every exercise below is a React component (or a Broken/Fixed pair) in its own .jsx file, paired with a .test.jsx that actually renders and interacts with it using Testing Library/Vitest - the same verified-output rule as every example in this course. No exercise makes a real network call: every test stubs fetch itself, the same way examples/01_loading_error_success_states.test.jsx does.
Exercise 1: A first modeled fetch - a restaurant menu loader
Scenario: A Zomato-style restaurant page needs to show its menu, with an explicit loading/error/success state - no booleans.
What to do: Write MenuLoader({ restaurantId }) that fetches `/api/restaurants/${restaurantId}/menu` inside a useEffect keyed on restaurantId, keeping exactly one state value shaped { phase: "loading" } / { phase: "error", message } / { phase: "success", data }, the same shape as examples/01_loading_error_success_states.jsx's OrderStatusModeled. Render a loading paragraph, an alert-role error paragraph, or a list of dish names.
Sample output (really run, restaurantId="R-9" resolves successfully):
first render -> "Loading menu..."
after fetch -> a <ul> with the dish names from the mocked response
💡 Hint: this is OrderStatusModeled with a menu array instead of a single order - one useState({ phase: "loading" }), replaced wholesale in every branch of the .then/.catch chain.
Exercise 2: Find and fix a boolean-soup bug
Scenario: A Swiggy-style delivery-partner ETA widget was written with three separate flags. A teammate wrote:
export function EtaWidgetBroken({ orderId }) {
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState(false);
const [etaMinutes, setEtaMinutes] = useState(null);
useEffect(() => {
setIsLoading(true);
// BUG: isError is never reset here
fetch(`/api/orders/${orderId}/eta`)
.then((res) => { if (!res.ok) throw new Error("eta unavailable"); return res.json(); })
.then((data) => { setEtaMinutes(data.etaMinutes); setIsLoading(false); })
.catch(() => { setIsError(true); setIsLoading(false); });
}, [orderId]);
if (isError) return <p role="alert">Could not load ETA</p>;
if (isLoading) return <p>Loading ETA...</p>;
return <p>Arriving in {etaMinutes} min</p>;
}
Testers report that once one order fails to load, every later order's ETA - even ones that load fine - keeps showing "Could not load ETA."
What to do: Write both EtaWidgetBroken (unchanged above) and EtaWidgetFixed, which collapses the three flags into one modeled state value, exactly like examples/01_loading_error_success_states.jsx's OrderStatusModeled.
Sample output (really run - mount with a failing orderId, then rerender with a succeeding one):
EtaWidgetBroken: stays on "Could not load ETA" forever, even after the second order's fetch really succeeds
EtaWidgetFixed: correctly shows "Arriving in 12 min" once the second order's fetch succeeds
💡 Hint: this is this part's Section 1 bug, renamed - the fix is deleting two of the three useState calls, not patching the missing reset.
Exercise 3: Prove and fix a race condition with AbortController
Scenario: An IRCTC-style PNR status box fetches a new PNR's status every time the input changes, with no cancellation.
What to do: Write PnrStatusBroken({ pnr }) with no cancellation at all (same shape as examples/02_race_condition_proven.jsx's RestaurantSearchRace), and PnrStatusFixed({ pnr }), which passes an AbortController's signal to fetch and aborts the previous request from the effect's cleanup function, the same shape as examples/03_abort_controller_cleanup.jsx's RestaurantSearchGuarded. Drive your test the same way examples/02_race_condition_proven.test.jsx and examples/03_abort_controller_cleanup.test.jsx do: control two requests' resolution order directly with deferred promises, so the race is reproduced on purpose, not left to timing.
Sample output (really run - mount with pnr="2001" (slow), rerender with pnr="2002" (fast), resolve "2002" first, then try to resolve "2001"):
PnrStatusBroken: ends up showing PNR 2001's stale status - the slower, earlier request overwrote the correct, newer one
PnrStatusFixed: ends up showing PNR 2002's status - 2001's request was aborted and its (attempted) resolution is a no-op
💡 Hint: the cleanup function is the entire fix - return () => controller.abort(); - nothing else about the component needs to change between the broken and fixed versions besides creating the controller and passing its signal.
Exercise 4: Find and fix a waterfall
Scenario: A BigBasket-style wallet screen needs a user's wallet balance and the current cashback offers - two requests that do not depend on each other at all, since the offers endpoint takes no user-specific data. A teammate wrote:
export function WalletScreenBroken() {
const [balance, setBalance] = useState(null);
const [offers, setOffers] = useState(null);
useEffect(() => {
fetch("/api/wallet/balance")
.then((res) => res.json())
.then((b) => { setBalance(b); return fetch("/api/offers/cashback").then((res) => res.json()); })
.then(setOffers);
}, []);
// ...
}
What to do: Write both WalletScreenBroken (unchanged above) and WalletScreenFixed, which starts both requests together with Promise.all, the same shape as examples/04_avoiding_waterfalls.jsx's TripDashboardParallel. Assert how many requests have started at specific points, the same way examples/04_avoiding_waterfalls.test.jsx does - not wall-clock time.
Sample output (really run, right after mounting each version, before either request resolves):
WalletScreenBroken: exactly 1 request has started ("/api/wallet/balance")
WalletScreenFixed: exactly 2 requests have started ("/api/wallet/balance" and "/api/offers/cashback")
💡 Hint: offers never reads anything from balance in either version - that is exactly what makes the sequential version a true waterfall (an unnecessary dependency), not a real one.
Exercise 5: Extract a shared useRideStatus hook
Scenario: An Ola/Uber-style ride screen has two separate widgets - a map pin label and an ETA banner - that both need the same ride's live status, but neither should know about fetch, AbortController, or the three-phase state shape directly.
What to do: Write useRideStatus(rideId), a custom hook with the identical shape as examples/05_use_fetch_custom_hook.jsx's useFetch (modeled state + AbortController cleanup), fetching `/api/rides/${rideId}/status`. Then write RideMapPin({ rideId }) and RideEtaBanner({ rideId }), both calling useRideStatus with the same rideId.
Sample output (really run, both components mounted together with the same rideId):
2 requests fired (one per component - each hook call has its own state and its own request)
RideMapPin shows: "Driver: 2 km away"
RideEtaBanner shows: "Arriving in 6 min"
💡 Hint: this is Part 7 Section 3's rule again - a custom hook shares logic, not a value. If the two widgets are meant to show the same fetched object without firing it twice, that needs the value lifted to a shared parent (or useContext, Part 9) - which this exercise deliberately does not ask for, to keep the independent-request behavior visible.
Exercise 6: A debounced, cancellable movie search box
Scenario: A BookMyShow-style movie search box should not fire a request on every keystroke, and whichever request is in flight when the user types again should be cancelled, not raced.
What to do: Combine Part 7's useDebounce with this part's AbortController pattern: write useMovieSearch(query), a hook that debounces query by 300ms (reuse or adapt useDebounce's shape), then fetches `/api/movies?q=${debouncedQuery}` with a cancellable AbortController-backed effect keyed on the debounced value, returning the same { phase } shape as useFetch. Write MovieSearchBox() using it, with a text input and a results list.
Sample output (vi.useFakeTimers() for the debounce, plus controlled fetch promises for the network - really run):
type "i" -> no request fired yet (debounce still waiting)
type "incep" (300ms after the last key) -> exactly 1 request fired, for "incep"
type "tion" quickly after -> the "incep" request is aborted; exactly 1 new request fired, for "inception"
resolve "inception"'s request -> results list shows "Inception (2010)"
💡 Hint: two timers are in play here and they are not the same thing - useDebounce's setTimeout (Part 7) delays which query gets used at all, while AbortController (this part) cancels whichever request is still in flight when a new debounced query arrives. Keying the fetch effect on the debounced value, not the raw query, is what makes the debounce apply before any request is even created.
Show the solutions for Part 11 (12 files)
solutions/ex01_menu_loader.jsx
// Exercise 1 solution: one modeled state value, the same shape as
// examples/01_loading_error_success_states.jsx's OrderStatusModeled -
// just fetching a menu array instead of a single order.
import { useEffect, useState } from "react";
export function MenuLoader({ restaurantId }) {
const [state, setState] = useState({ phase: "loading" });
useEffect(() => {
setState({ phase: "loading" });
fetch(`/api/restaurants/${restaurantId}/menu`)
.then((res) => {
if (!res.ok) throw new Error(`menu for ${restaurantId} unavailable`);
return res.json();
})
.then((data) => setState({ phase: "success", data }))
.catch((error) => setState({ phase: "error", message: error.message }));
}, [restaurantId]);
if (state.phase === "loading") return <p>Loading menu...</p>;
if (state.phase === "error") return <p role="alert">{state.message}</p>;
return (
<ul>
{state.data.dishes.map((dish) => (
<li key={dish}>{dish}</li>
))}
</ul>
);
}
solutions/ex01_menu_loader.test.jsx
import { render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { MenuLoader } from "./ex01_menu_loader.jsx";
function fakeResponse(body, { ok = true } = {}) {
return { ok, json: () => Promise.resolve(body) };
}
afterEach(() => {
vi.unstubAllGlobals();
});
describe("MenuLoader models loading/error/success as one value", () => {
it("really shows loading, then the dish list, for a good restaurant", async () => {
vi.stubGlobal(
"fetch",
vi.fn(() => Promise.resolve(fakeResponse({ dishes: ["Paneer Tikka", "Dal Makhani", "Butter Naan"] }))),
);
render(<MenuLoader restaurantId="R-9" />);
expect(screen.getByText("Loading menu...")).toBeInTheDocument();
expect(await screen.findByText("Paneer Tikka")).toBeInTheDocument();
expect(screen.getByText("Dal Makhani")).toBeInTheDocument();
expect(screen.getByText("Butter Naan")).toBeInTheDocument();
});
it("really shows an alert for a restaurant with no menu", async () => {
vi.stubGlobal("fetch", vi.fn(() => Promise.resolve(fakeResponse({ error: "not found" }, { ok: false }))));
render(<MenuLoader restaurantId="R-404" />);
expect(await screen.findByRole("alert")).toHaveTextContent("menu for R-404 unavailable");
});
});
solutions/ex02_eta_widget.jsx
// Exercise 2 solution: same bug and fix as
// examples/01_loading_error_success_states.jsx - three independent flags
// let a stale isError linger behind a real, later success; the fix is
// collapsing them into one modeled state value, not patching a reset.
import { useEffect, useState } from "react";
export function EtaWidgetBroken({ orderId }) {
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState(false);
const [etaMinutes, setEtaMinutes] = useState(null);
useEffect(() => {
setIsLoading(true);
// BUG: isError is never reset to false here.
fetch(`/api/orders/${orderId}/eta`)
.then((res) => {
if (!res.ok) throw new Error("eta unavailable");
return res.json();
})
.then((data) => {
setEtaMinutes(data.etaMinutes);
setIsLoading(false);
})
.catch(() => {
setIsError(true);
setIsLoading(false);
});
}, [orderId]);
if (isError) return <p role="alert">Could not load ETA</p>;
if (isLoading) return <p>Loading ETA...</p>;
return <p>Arriving in {etaMinutes} min</p>;
}
export function EtaWidgetFixed({ orderId }) {
const [state, setState] = useState({ phase: "loading" });
useEffect(() => {
setState({ phase: "loading" });
fetch(`/api/orders/${orderId}/eta`)
.then((res) => {
if (!res.ok) throw new Error("eta unavailable");
return res.json();
})
.then((data) => setState({ phase: "success", etaMinutes: data.etaMinutes }))
.catch(() => setState({ phase: "error" }));
}, [orderId]);
if (state.phase === "error") return <p role="alert">Could not load ETA</p>;
if (state.phase === "loading") return <p>Loading ETA...</p>;
return <p>Arriving in {state.etaMinutes} min</p>;
}
solutions/ex02_eta_widget.test.jsx
import { render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { EtaWidgetBroken, EtaWidgetFixed } from "./ex02_eta_widget.jsx";
function fakeResponse(body, { ok = true } = {}) {
return { ok, json: () => Promise.resolve(body) };
}
function installMockFetch() {
vi.stubGlobal(
"fetch",
vi.fn((url) => {
if (url.includes("BAD")) return Promise.resolve(fakeResponse({ error: "no eta" }, { ok: false }));
return Promise.resolve(fakeResponse({ etaMinutes: 12 }));
}),
);
}
afterEach(() => {
vi.unstubAllGlobals();
});
describe("EtaWidgetBroken keeps a stale error flag after a later order succeeds", () => {
it("really stays stuck on the error, even though the second order's fetch really succeeds", async () => {
installMockFetch();
const { rerender } = render(<EtaWidgetBroken orderId="BAD-1" />);
expect(await screen.findByRole("alert")).toHaveTextContent("Could not load ETA");
rerender(<EtaWidgetBroken orderId="GOOD-2" />);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(screen.getByRole("alert")).toHaveTextContent("Could not load ETA");
expect(screen.queryByText("Arriving in 12 min")).not.toBeInTheDocument();
});
});
describe("EtaWidgetFixed has no flag left to go stale", () => {
it("really shows the correct ETA once the second order's fetch succeeds", async () => {
installMockFetch();
const { rerender } = render(<EtaWidgetFixed orderId="BAD-1" />);
expect(await screen.findByRole("alert")).toHaveTextContent("Could not load ETA");
rerender(<EtaWidgetFixed orderId="GOOD-2" />);
expect(await screen.findByText("Arriving in 12 min")).toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
});
solutions/ex03_pnr_status.jsx
// Exercise 3 solution: same shapes as examples/02_race_condition_proven.jsx
// (no protection) and examples/03_abort_controller_cleanup.jsx (the fix) -
// a new PNR fetch cancels the previous one instead of racing it.
import { useEffect, useState } from "react";
export function PnrStatusBroken({ pnr }) {
const [status, setStatus] = useState("");
useEffect(() => {
fetch(`/api/pnr/${pnr}`)
.then((res) => res.json())
.then((data) => setStatus(data.status));
}, [pnr]);
return <p>PNR {pnr}: {status || "..."}</p>;
}
export function PnrStatusFixed({ pnr }) {
const [status, setStatus] = useState("");
useEffect(() => {
const controller = new AbortController();
fetch(`/api/pnr/${pnr}`, { signal: controller.signal })
.then((res) => res.json())
.then((data) => setStatus(data.status))
.catch((error) => {
if (error.name === "AbortError") return;
throw error;
});
return () => controller.abort();
}, [pnr]);
return <p>PNR {pnr}: {status || "..."}</p>;
}
solutions/ex03_pnr_status.test.jsx
import { render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { PnrStatusBroken, PnrStatusFixed } from "./ex03_pnr_status.jsx";
function fakeResponse(body) {
return { ok: true, json: () => Promise.resolve(body) };
}
function installAbortAwareFetch() {
const deferredByPnr = {};
vi.stubGlobal(
"fetch",
vi.fn((url, { signal } = {}) => {
const pnr = url.split("/").pop();
return new Promise((resolve, reject) => {
deferredByPnr[pnr] = resolve;
signal?.addEventListener("abort", () => {
const error = new Error("The operation was aborted.");
error.name = "AbortError";
reject(error);
});
});
}),
);
return deferredByPnr;
}
afterEach(() => {
vi.unstubAllGlobals();
});
describe("PnrStatusBroken lets the slower, earlier PNR overwrite the faster, later one", () => {
it("really ends up showing PNR 2001's stale status", async () => {
const deferredByPnr = installAbortAwareFetch();
const { rerender } = render(<PnrStatusBroken pnr="2001" />);
rerender(<PnrStatusBroken pnr="2002" />);
deferredByPnr["2002"](fakeResponse({ status: "WL" }));
await screen.findByText("PNR 2002: WL");
deferredByPnr["2001"](fakeResponse({ status: "CNF" }));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(screen.getByText("PNR 2002: CNF")).toBeInTheDocument();
});
});
describe("PnrStatusFixed aborts the stale PNR request before it can overwrite anything", () => {
it("really keeps showing PNR 2002's status - 2001's request was cancelled", async () => {
const deferredByPnr = installAbortAwareFetch();
const { rerender } = render(<PnrStatusFixed pnr="2001" />);
rerender(<PnrStatusFixed pnr="2002" />);
deferredByPnr["2002"](fakeResponse({ status: "WL" }));
await screen.findByText("PNR 2002: WL");
// 2001's request already rejected with AbortError when it was
// cancelled above; this attempted resolve is a no-op.
deferredByPnr["2001"](fakeResponse({ status: "CNF" }));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(screen.getByText("PNR 2002: WL")).toBeInTheDocument();
});
});
solutions/ex04_wallet_screen.jsx
// Exercise 4 solution: same shape as examples/04_avoiding_waterfalls.jsx -
// offers never read anything from balance, so there is no real reason for
// one request to wait on the other.
import { useEffect, useState } from "react";
export function WalletScreenBroken() {
const [balance, setBalance] = useState(null);
const [offers, setOffers] = useState(null);
useEffect(() => {
fetch("/api/wallet/balance")
.then((res) => res.json())
.then((b) => {
setBalance(b);
return fetch("/api/offers/cashback").then((res) => res.json());
})
.then(setOffers);
}, []);
if (!balance || !offers) return <p>Loading wallet...</p>;
return <p>Balance: ₹{balance.amount} - {offers.count} cashback offers</p>;
}
export function WalletScreenFixed() {
const [balance, setBalance] = useState(null);
const [offers, setOffers] = useState(null);
useEffect(() => {
Promise.all([
fetch("/api/wallet/balance").then((res) => res.json()),
fetch("/api/offers/cashback").then((res) => res.json()),
]).then(([b, o]) => {
setBalance(b);
setOffers(o);
});
}, []);
if (!balance || !offers) return <p>Loading wallet...</p>;
return <p>Balance: ₹{balance.amount} - {offers.count} cashback offers</p>;
}
solutions/ex04_wallet_screen.test.jsx
import { render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { WalletScreenBroken, WalletScreenFixed } from "./ex04_wallet_screen.jsx";
function installControllableFetch() {
const deferredByUrl = {};
const fetchMock = vi.fn((url) => new Promise((resolve) => { deferredByUrl[url] = resolve; }));
vi.stubGlobal("fetch", fetchMock);
return { fetchMock, deferredByUrl };
}
function fakeResponse(body) {
return { ok: true, json: () => Promise.resolve(body) };
}
afterEach(() => {
vi.unstubAllGlobals();
});
describe("WalletScreenBroken waterfalls two independent requests", () => {
it("really has made exactly one request right after mount", () => {
const { fetchMock } = installControllableFetch();
render(<WalletScreenBroken />);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith("/api/wallet/balance");
});
it("really finishes correctly once both requests resolve in order", async () => {
const { fetchMock, deferredByUrl } = installControllableFetch();
render(<WalletScreenBroken />);
deferredByUrl["/api/wallet/balance"](fakeResponse({ amount: 450 }));
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
deferredByUrl["/api/offers/cashback"](fakeResponse({ count: 3 }));
expect(await screen.findByText("Balance: ₹450 - 3 cashback offers")).toBeInTheDocument();
});
});
describe("WalletScreenFixed starts both requests together", () => {
it("really has made both requests right after mount, before either resolves", () => {
const { fetchMock } = installControllableFetch();
render(<WalletScreenFixed />);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock).toHaveBeenCalledWith("/api/wallet/balance");
expect(fetchMock).toHaveBeenCalledWith("/api/offers/cashback");
});
it("really finishes correctly no matter which request resolves first", async () => {
const { deferredByUrl } = installControllableFetch();
render(<WalletScreenFixed />);
deferredByUrl["/api/offers/cashback"](fakeResponse({ count: 3 }));
deferredByUrl["/api/wallet/balance"](fakeResponse({ amount: 450 }));
expect(await screen.findByText("Balance: ₹450 - 3 cashback offers")).toBeInTheDocument();
});
});
solutions/ex05_ride_status_hook.jsx
// Exercise 5 solution: same shape as examples/05_use_fetch_custom_hook.jsx -
// one hook packaging modeled state + AbortController cleanup, called
// independently by two different widgets that need the same ride's data.
import { useEffect, useState } from "react";
export function useRideStatus(rideId) {
const [state, setState] = useState({ phase: "loading" });
useEffect(() => {
const controller = new AbortController();
setState({ phase: "loading" });
fetch(`/api/rides/${rideId}/status`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`ride ${rideId} not found`);
return res.json();
})
.then((data) => setState({ phase: "success", data }))
.catch((error) => {
if (error.name === "AbortError") return;
setState({ phase: "error", message: error.message });
});
return () => controller.abort();
}, [rideId]);
return state;
}
export function RideMapPin({ rideId }) {
const state = useRideStatus(rideId);
if (state.phase !== "success") return <p>...</p>;
return <p>Driver: {state.data.distanceKm} km away</p>;
}
export function RideEtaBanner({ rideId }) {
const state = useRideStatus(rideId);
if (state.phase !== "success") return <p>...</p>;
return <p>Arriving in {state.data.etaMinutes} min</p>;
}
solutions/ex05_ride_status_hook.test.jsx
import { render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { RideEtaBanner, RideMapPin } from "./ex05_ride_status_hook.jsx";
function fakeResponse(body) {
return { ok: true, json: () => Promise.resolve(body) };
}
afterEach(() => {
vi.unstubAllGlobals();
});
describe("useRideStatus gives each widget its own independent request", () => {
it("really fires two requests for two widgets sharing the same rideId", async () => {
const fetchMock = vi.fn(() => Promise.resolve(fakeResponse({ distanceKm: 2, etaMinutes: 6 })));
vi.stubGlobal("fetch", fetchMock);
render(
<>
<RideMapPin rideId="RIDE-1" />
<RideEtaBanner rideId="RIDE-1" />
</>,
);
expect(await screen.findByText("Driver: 2 km away")).toBeInTheDocument();
expect(await screen.findByText("Arriving in 6 min")).toBeInTheDocument();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});
solutions/ex06_movie_search.jsx
// Exercise 6 solution: Part 7's useDebounce shape delays which query is
// used at all; this part's AbortController shape cancels whichever
// request is still in flight once a new debounced query arrives. The
// fetch effect is keyed on the DEBOUNCED value, not the raw query, so the
// debounce happens before any request is ever created.
import { useEffect, useState } from "react";
function useDebouncedValue(value, delayMs) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timeoutId = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(timeoutId);
}, [value, delayMs]);
return debounced;
}
export function useMovieSearch(query) {
const debouncedQuery = useDebouncedValue(query, 300);
const [state, setState] = useState({ phase: "idle" });
useEffect(() => {
if (!debouncedQuery) {
setState({ phase: "idle" });
return;
}
const controller = new AbortController();
setState({ phase: "loading" });
fetch(`/api/movies?q=${debouncedQuery}`, { signal: controller.signal })
.then((res) => res.json())
.then((data) => setState({ phase: "success", data }))
.catch((error) => {
if (error.name === "AbortError") return;
setState({ phase: "error", message: error.message });
});
return () => controller.abort();
}, [debouncedQuery]);
return state;
}
export function MovieSearchBox() {
const [query, setQuery] = useState("");
const state = useMovieSearch(query);
return (
<div>
<input aria-label="search movies" value={query} onChange={(e) => setQuery(e.target.value)} />
{state.phase === "success" && (
<ul>
{state.data.results.map((title) => (
<li key={title}>{title}</li>
))}
</ul>
)}
</div>
);
}
solutions/ex06_movie_search.test.jsx
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MovieSearchBox } from "./ex06_movie_search.jsx";
function fakeResponse(body) {
return { ok: true, json: () => Promise.resolve(body) };
}
function installAbortAwareFetch() {
const deferredByQuery = {};
const fetchMock = vi.fn((url, { signal } = {}) => {
const query = new URL(url, "http://localhost").searchParams.get("q");
return new Promise((resolve, reject) => {
deferredByQuery[query] = resolve;
signal?.addEventListener("abort", () => {
const error = new Error("The operation was aborted.");
error.name = "AbortError";
reject(error);
});
});
});
vi.stubGlobal("fetch", fetchMock);
return { fetchMock, deferredByQuery };
}
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
describe("useMovieSearch debounces the query, then cancels a stale request", () => {
it("really fires one request per settled query, cancelling whatever was still in flight", async () => {
const { fetchMock, deferredByQuery } = installAbortAwareFetch();
render(<MovieSearchBox />);
const input = screen.getByLabelText("search movies");
fireEvent.change(input, { target: { value: "i" } });
act(() => vi.advanceTimersByTime(299));
expect(fetchMock).not.toHaveBeenCalled();
// Typing stops for a full 300ms on "incep" - the debounce settles and
// fires exactly one request.
fireEvent.change(input, { target: { value: "incep" } });
act(() => vi.advanceTimersByTime(300));
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith("/api/movies?q=incep", expect.anything());
// The user keeps typing before "incep" resolves. Once typing stops
// again, the debounce settles on "inception" - this cancels "incep"'s
// still-pending request and fires exactly one new one.
fireEvent.change(input, { target: { value: "inception" } });
act(() => vi.advanceTimersByTime(300));
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock).toHaveBeenCalledWith("/api/movies?q=inception", expect.anything());
// "incep"'s request already rejected with AbortError when it was
// cancelled; resolving it now is a no-op.
deferredByQuery["incep"](fakeResponse({ results: ["Inceptionist (fan film)"] }));
deferredByQuery["inception"](fakeResponse({ results: ["Inception (2010)"] }));
// Testing Library's findBy* polls with a real setTimeout, which fake
// timers never advance on their own - flush the pending microtasks
// (the resolved fetches' .then chains) directly instead, then query
// synchronously, the same way every other fake-timer test in this
// course avoids mixing the two timer worlds.
await act(async () => {
await Promise.resolve();
});
expect(screen.getByText("Inception (2010)")).toBeInTheDocument();
expect(screen.queryByText("Inceptionist (fan film)")).not.toBeInTheDocument();
});
});
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Modeling a fetch's status as separate isLoading/isError/data booleans |
Nothing forces the three to be updated together - a forgotten reset leaves one flag telling a stale story even after the real request already succeeded | Use one state value that can only ever be exactly one of a fixed set of shapes ({ phase: "loading" } / "error" / "success" ), replaced wholesale on every fetch (Section 1) |
| Fetching on every id/query change with no protection against an older request resolving later | A slower, earlier request can finish after a faster, later one and silently overwrite the correct, newer result on screen | Cancel the previous request from the effect's cleanup function with AbortController before starting a new one (Section 2-3) |
Treating every fetch rejection the same way, including AbortError |
A cancelled request is not a failure - showing an error message for a request you cancelled on purpose confuses a correct cancellation with a real outage | Check error.name === "AbortError" in the catch and return quietly; re-throw (or report) anything else (Section 3) |
Fetching B inside A's .then, when B does not actually need anything A returned |
Two independent requests end up costing as long as both, one after another, instead of running at the same time | Start every request that does not depend on another's result together, with Promise.all (Section 4) |
| Writing the loading/error/success dance by hand inside every component that fetches something | Same root duplicated-logic problem Part 7 named for useLocalStorage/useDebounce, now around a network call instead of a browser API |
Extract a useFetch(url) hook once (Section 5); every caller still gets its own independent request and state |
Quick recap
- A fetch's status is one value with exactly one of a few shapes at a time, never several independent booleans that nothing keeps in agreement with each other.
- Fetching-in-an-effect has a real race condition: a slower, earlier request can resolve after a faster, later one and overwrite it - reproducible on demand by controlling resolution order yourself, not something that merely "sometimes happens."
AbortControllercancels the stale request itself (not just its effect on state) from the same cleanup function Part 6 already taught; a cancelled fetch rejects withAbortError, which is "nothing to do," not a failure to report.- Two requests that do not depend on each other belong under
Promise.all, started in the same tick - coding them one after another (a waterfall) costs the sum of both for no benefit. - A
useFetch(url)custom hook moves loading/error/success modeling andAbortControllercleanup into one place; every component that calls it still gets its own independent request, the same guarantee Part 7 already established for any custom hook. - Nothing in this part talks to a real server - every test stubs
fetchitself, so every result is offline, deterministic, and exactly reproducible.
Checklist
- I can say, in one sentence, why three independent booleans are a worse fetch-status model than one value with a fixed set of shapes.
- I reproduced the boolean-soup bug myself - a flag that is never reset, leaving a component stuck on a stale branch even after the real data loaded - then fixed it by collapsing the flags into one state value.
- I reproduced the race condition myself by controlling two requests' resolution order directly, watched a slower earlier response overwrite a faster later one, then fixed it with
AbortController. - I can explain what
error.name === "AbortError"is checking for, and why treating it as a real failure would be wrong. - I found (or wrote) two independent requests coded as a waterfall, proved the wasted wait by counting how many requests had started at a given point, and fixed it with
Promise.all. - I extracted a
useFetch(url)hook, used it from two different components with the same url, and confirmed each one fired its own request.