Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Project

Book Finder

Start after Part 14

Stage 3

Goal: Search a real public API from a component, model loading/error/empty/success as one explicit phase value (never boolean soup), guarantee a fast second search can never show a slow first search's stale result, contain a crash in the results panel with a real error boundary, and code-split one component with React.lazy/Suspense - then prove every one of those claims with a Vitest + Testing Library suite that makes zero real network calls. Time: ~6 hours · Uses: Part 11 (fetching data, modeled state, AbortController), Part 13 (error boundaries, React.lazy/Suspense), Part 14 (Testing Library query priority, user-event, findBy*/waitFor)

Project brief

This is the stage's own project, straight from the stage plan: a search box against Open Library's free, no-API-key search.json endpoint, with every failure mode a real app has to handle instead of pretending they don't exist - a slow network, a request that fails outright, a query with no matches, and a second search fired before the first one has even come back. The books list, author names, and publish years below all come straight off the real response shape (numFound, docs[].title, docs[].author_name, docs[].first_publish_year) - nothing invented.

Search: "dune"                → Searching...  →  Dune — Frank Herbert — 1965
Search: "zzzznoresults"       → No books found for "zzzznoresults".
(network down)                → ⚠ Failed to fetch
Search "dune", then "hobbit"
before "dune" even resolves   → only The Hobbit ever appears - "dune"'s
                                 slower, stale response never overwrites it

Files

File What it is
README.md This brief and the step-by-step build guide
useBookSearch.js The custom hook: owns the { phase } state and an AbortController per search, aborting whatever is still in flight whenever a new search starts or the component unmounts
SearchForm.jsx A controlled text input + submit button; calls search(query) on submit
ResultsPanel.jsx The lazily-loaded (React.lazy) panel: renders the right UI for idle/loading/error/empty-success/success-with-results
BookList.jsx Renders the actual <ul> of books - title, authors, year - and is the one place that deliberately throws, if handed a doc with no title
ErrorBoundary.jsx Part 13's class-based boundary (getDerivedStateFromError/componentDidCatch), wrapping the results panel
BookFinder.jsx Composes all of the above into the one component this project ships
useBookSearch.test.jsx The hook tested in isolation via renderHook - phases, cancellation, and the no-stale-race proof
BookFinder.test.jsx The whole app wired together - every feature below is actually driven through the UI and asserted on

How to run

This project reuses the one repo-level harness (Vitest + Testing Library, see ../../TOOLING.md) - no separate install, no separate package.json. From the repo root:

npx vitest run stage-3-advanced/project-book-finder

To actually see it render, add <BookFinder /> to harness/src/App.jsx temporarily (import it from this folder) and run npm run dev - then remove the import again once you are done, so the harness keeps showing whichever part it is currently wired for.

Features

Feature What it does
Submit-based search Typing and pressing "Search" calls search(query) once, on submit - simpler to wire and deterministic to test than debounce-on-type, and the stage plan explicitly allows either
Explicit phase state { phase: "idle" | "loading" | "error" | "success" }, exactly Part 11's modeled-state shape - never a loading/error/data triple of booleans guessed from each other
Request cancellation Every search() call aborts whatever AbortController is still live from the previous call before starting a new one, and aborts on unmount too
No stale-result race Because the previous request is aborted (not just ignored), a fast second search's result can never be overwritten by a slower first one that resolves later
Distinct empty state Zero matches shows No books found for "<query>". - a real, different message from the error state, not a silently empty list
Error state A failed request (rejected fetch, or a non-ok response) shows role="alert" with the real error message
Error boundary Wraps the results panel; a thrown render error (a doc missing title) is contained behind a "Try again" fallback instead of blanking the whole app
Code-split results panel ResultsPanel is loaded with React.lazy() behind a <Suspense fallback={<p>Loading results view...</p>}>

Which Parts each feature uses

Feature Skills Part
useBookSearch's { phase } state Modeling loading/error/success as one value, not boolean soup Part 11, Section 1
The no-stale-race proof in useBookSearch.test.jsx Reproducing a request race for real, with controllable promises instead of real timing Part 11, Section 2
AbortController per search, aborted on the next search and on unmount Cancelling an in-flight request with AbortController and a cleanup function Part 11, Section 3
useBookSearch itself, as an extracted, reusable hook Packaging a fetch + modeled state + cancellation once, instead of per component Part 11, Section 5
ErrorBoundary wrapping ResultsPanel, catching BookList's thrown render error A class boundary (getDerivedStateFromError/componentDidCatch) with a render-prop fallback Part 13, Section 2
ResultsPanel = lazy(() => import("./ResultsPanel.jsx")) behind a <Suspense> Code-splitting a component with React.lazy/Suspense and a real fallback Part 13, Section 4
Every test's queries (getByRole, getByLabelText, findByRole) Testing Library's query-priority order - role/label/text before any test id Part 14, Section 1
userEvent.type/userEvent.click driving the real <form> user-event over fireEvent for anything resembling real user interaction Part 14, Section 2
await screen.findByRole("alert"), await waitFor(() => ...) findBy* for DOM queries, waitFor for a non-DOM assertion (a hook's own state) Part 14, Section 3
useBookSearch.test.jsx's renderHook tests Testing a hook's own contract directly, with no UI standing in the way Part 14, Section 5

💡 No mocking library beyond Vitest's own vi.fn/vi.stubGlobal is used anywhere in this project's tests - every fetch call in every test file is a hand-installed mock, never the real network. There is one call site that mentions fetch( in a comment only (useBookSearch.test.jsx); grep the test files yourself to confirm.


Build it step by step

Build in small steps. Run the tests after every step. Do not open the finished files until you have tried each step yourself.

Step 1: Model the state (Part 11, Section 1)

What and why: decide the shape of "what this search is doing right now" before writing a single line of UI. One value, never three flags.

// useBookSearch.js
const [state, setState] = useState({ phase: "idle" });
// { phase: "idle" } | { phase: "loading" } | { phase: "error", message }
// | { phase: "success", data: { numFound, docs }, query }

✅ Test: call search() with a mocked successful response and confirm the hook's returned state really becomes { phase: "success", data: { numFound, docs }, query } - not a boolean pair.

Step 2: Fetch on submit, not on every keystroke

What and why: the stage plan allows either "on submit" or "debounced on type" - submit is simpler to wire and, critically, deterministic to test: one search(query) call per submit event, no timers involved at all.

// SearchForm.jsx
function handleSubmit(event) {
  event.preventDefault();
  onSearch(query);
}

✅ Test: typing into the input and clicking "Search" (via user-event, Part 14 Section 2) calls the mocked fetch exactly once, with the submitted query in the URL.

Step 3: Cancel the previous request (Part 11, Section 3)

What and why: every search() call must abort whatever AbortController the previous call created, before starting its own - otherwise a slow first request can still finish after a faster second one and silently overwrite it.

const search = useCallback((rawQuery) => {
  controllerRef.current?.abort();
  const controller = new AbortController();
  controllerRef.current = controller;
  // ...fetch(url, { signal: controller.signal })...
}, []);

✅ Test: call search("dune"), capture the mocked fetch's signal argument, call search("hobbit"), and assert the first signal's .aborted is now true.

Step 4: Prove the race is actually fixed, not just "probably fine" (Part 11, Section 2)

What and why: this is the stage project's core acceptance claim, and the only way to prove it is to control both requests' resolution order directly, the same way Part 11's race-condition example does.

// useBookSearch.test.jsx
act(() => result.current.search("dune"));
act(() => result.current.search("hobbit"));
deferredByQuery["hobbit"](fakeResponse({ ...theHobbit }));
await waitFor(() => expect(result.current.state.phase).toBe("success"));
// "dune" resolving now, after being aborted, has no effect at all:
deferredByQuery["dune"]?.(fakeResponse({ ...dune }));

✅ Test: after both deferred promises settle (newer first, stale one second), the hook's state still shows only the newer result.

Step 5: Distinct empty, error, and success UI (Part 11, Section 1)

What and why: zero matches is not an error, and an error is not a silently empty list - each phase gets its own real message.

// ResultsPanel.jsx
if (state.phase === "error") return <p role="alert">{state.message}</p>;
if (numFound === 0 || docs.length === 0) return <p>No books found for "{state.query}".</p>;
return <BookList books={docs} />;

✅ Test: a mocked zero-match response shows the "No books found" text and screen.queryByRole("alert") is null; a mocked rejected/!ok response shows role="alert" with the real message.

Step 6: Contain a render crash (Part 13, Section 2)

What and why: BookList deliberately throws if handed a doc with no title, so there is a genuine, reproducible render error to prove the boundary actually does something, not just exist unused.

// BookList.jsx
if (!book.title) throw new Error(`Book result ${book.key} is missing a title and cannot be rendered`);

ErrorBoundary wraps ResultsPanel in BookFinder.jsx, with a fallback that renders role="alert" and a "Try again" button.

✅ Test: mock a response with one doc missing title, submit a search, and confirm screen.findByRole("alert") shows the boundary's fallback text (not the app crashing) and the search form is still on screen.

Step 7: Code-split the results panel (Part 13, Section 4)

What and why: ResultsPanel is the one component most likely to grow, and the one piece nobody needs downloaded before they've typed a query.

// BookFinder.jsx
const ResultsPanel = lazy(() => import("./ResultsPanel.jsx"));
// ...
<Suspense fallback={<p>Loading results view...</p>}>
  <ResultsPanel state={state} />
</Suspense>

✅ Test: render <BookFinder /> and confirm "Loading results view..." is on screen first, then await screen.findByText(...) confirms the real idle message renders once the chunk resolves.


Stretch goals

  • 🟢 A "Clear results" button that resets the hook back to { phase: "idle" } without a new fetch.
  • 🟡 Debounce-on-type as an alternative input mode (Part 7's useDebouncedValue shape, same as Part 11's movie-search exercise), toggled alongside the existing submit button.
  • 🟡 A cover image per result (https://covers.openlibrary.org/b/id/{cover_i}-M.jpg), with a graceful fallback for docs that have no cover_i.
  • 🔴 Pagination using Open Library's page/limit query params, with its own loading state for "load more" that does not reset the results already shown.
  • 🔴 A reset-pattern retry (Part 13, Section 3) on the error boundary's fallback, so "Try again" actually refetches instead of just clearing the boundary's own error state.

Checklist

  • I modeled search state as one { phase } value, never a loading/error/data boolean trio.
  • Every search() call aborts the previous call's still-live AbortController before starting its own, and I proved this with a captured signal.aborted.
  • I reproduced the stale-result race on purpose, with controllable promises resolved in a deliberately "wrong" order, and proved the newer result wins.
  • Idle, loading, error, empty-success, and success-with-results each render visibly different, real UI.
  • The error boundary around the results panel actually catches a real thrown render error in a test, not just an untested <ErrorBoundary> wrapper.
  • ResultsPanel is loaded with React.lazy/Suspense, with a real fallback shown and tested.
  • npx vitest run stage-3-advanced/project-book-finder passes, start to finish, with zero real network calls anywhere in the suite.

Next

🎉 Stage 3 done! Go back to the roadmap and start Stage 4: Routing and application architecture.

Search the guide