Skip to the code

Start each query as early as it can

Each tea's page at Leaf and Kettle, app/teas/[slug]/page.tsx, needs three queries from @/lib/shop: getTea(slug), which takes 100 ms; the tea's reviews, getReviews(slug), 300 ms; and the teas of the same type, getTeasOfType(tea.type), 150 ms. One after another, as the page runs them now, they take 550 ms.

Make the page ready as soon as the data allows. The reviews only need the slug, so start them together with the tea. The teas of its type need the tea's type, so start that query the moment the tea arrives, without waiting for the reviews. Done right, the page is ready in 300 ms. Each query runs once, and started in lib/shop.ts lists them as they begin.

When there's no such tea, call notFound() as soon as getTea says so, without waiting for the reviews.

The reviews service sometimes goes down, and then getReviews rejects. The page must still show, with Reviews are unavailable right now. in the reviews section.

Keep what the page shows: the tea's name in an <h1>; a <section> headed Reviews with each review as an <li>, like Fresh, like spring. (Kenji), or No reviews yet. when there are none; and a <section> headed with the type, like More green teas, with a link to each other tea of the type at /teas/<slug>.

0 ms    getTea("sencha") and getReviews("sencha") start
100 ms  the tea is in, so getTeasOfType("green") starts
250 ms  the green teas are in
300 ms  the reviews are in: the page is ready

The app's other files

lib/shop.ts, read-only. Import it as @/lib/shop.

export type Tea = { slug: string; name: string; type: string };
export type Review = { author: string; text: string };
 
/** The queries that have started, in order: what the database would see. */
export const started: string[] = [];
 
/** Set `down` to true and the reviews service fails, as it sometimes does. */
export const reviewsService = { down: false };
 
/** How long the database takes to answer. */
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
 
const teas: Tea[] = [
  { slug: "sencha", name: "Sencha", type: "green" },
  { slug: "matcha", name: "Matcha", type: "green" },
  { slug: "gyokuro", name: "Gyokuro", type: "green" },
  { slug: "assam", name: "Assam", type: "black" },
];
 
const reviews: Record<string, Review[]> = {
  sencha: [
    { author: "Kenji", text: "Fresh, like spring." },
    { author: "Ana", text: "My morning cup." },
  ],
};
 
/** The tea with this slug, or undefined when the shop doesn't sell it. Takes 100 ms. */
export async function getTea(slug: string): Promise<Tea | undefined> {
  started.push(`tea ${slug}`);
  await wait(100);
  return teas.find((tea) => tea.slug === slug);
}
 
/** A tea's reviews, from the reviews service. Takes 300 ms, then rejects if the service is down. */
export async function getReviews(slug: string): Promise<Review[]> {
  started.push(`reviews ${slug}`);
  await wait(300);
  if (reviewsService.down) throw new Error("The reviews service is down");
  return reviews[slug] ?? [];
}
 
/** Every tea of a type, like "green". Takes 150 ms. */
export async function getTeasOfType(type: string): Promise<Tea[]> {
  started.push(`type ${type}`);
  await wait(150);
  return teas.filter((tea) => tea.type === type);
}

What the tests check

  1. shows the tea, its reviews, and the other teas of its type
    const clock = useFakeTimers();
    const rendering = renderServer(<Page params={params({ slug: "sencha" })} />);
    await flush();
    await clock.advance(1000);
    await rendering;
    expect(screen.getByRole("heading", { level: 1, name: "Sencha" })).toBeInTheDocument();
    const reviews = within(screen.getByRole("heading", { name: "Reviews" }).closest("section"));
    expect(reviews.getAllByRole("listitem").map((item) => item.textContent)).toEqual(["Fresh, like spring. (Kenji)", "My morning cup. (Ana)"]);
    const more = within(screen.getByRole("heading", { name: "More green teas" }).closest("section"));
    expect(more.getAllByRole("link").map((link) => [link.textContent, link.getAttribute("href")])).toEqual([
      ["Matcha", "/teas/matcha"],
      ["Gyokuro", "/teas/gyokuro"],
    ]);
    
  2. says No reviews yet. for a tea without reviews
    const clock = useFakeTimers();
    const rendering = renderServer(<Page params={params({ slug: "assam" })} />);
    await flush();
    await clock.advance(1000);
    await rendering;
    const reviews = within(screen.getByRole("heading", { name: "Reviews" }).closest("section"));
    expect(reviews.getByText("No reviews yet.")).toBeInTheDocument();
    expect(screen.getByRole("heading", { name: "More black teas" })).toBeInTheDocument();
    
  3. starts the reviews with the tea, and the teas of its type once the tea is in
    const clock = useFakeTimers();
    const rendering = renderServer(<Page params={params({ slug: "sencha" })} />);
    await flush();
    expect([...started].sort()).toEqual(["reviews sencha", "tea sencha"]);
    await clock.advance(100);
    expect(started).toContain("type green");
    await clock.advance(1000);
    await rendering;
    expect(started.length).toBe(3);
    
  4. is ready in 300 ms, when the slowest query is
    const clock = useFakeTimers();
    const start = Date.now();
    let readyAfter = null;
    const rendering = renderServer(<Page params={params({ slug: "sencha" })} />).then(() => (readyAfter = Date.now() - start));
    await flush();
    await clock.advance(1000);
    await rendering;
    expect(readyAfter).toBe(300);
    
  5. still shows the page when the reviews service is down
    reviewsService.down = true;
    const clock = useFakeTimers();
    const rendering = renderServer(<Page params={params({ slug: "sencha" })} />);
    await flush();
    await clock.advance(1000);
    await rendering;
    expect(screen.getByRole("heading", { level: 1, name: "Sencha" })).toBeInTheDocument();
    expect(screen.getByText("Reviews are unavailable right now.")).toBeInTheDocument();
    expect(screen.getByRole("link", { name: "Matcha" })).toHaveAttribute("href", "/teas/matcha");
    
  6. calls notFound() as soon as it knows there's no such tea
    const clock = useFakeTimers();
    let status = null;
    const answered = accessErrorOf(() => renderServer(<Page params={params({ slug: "coffee" })} />)).then((code) => (status = code));
    await flush();
    await clock.advance(100);
    expect(status).toBe(404);
    await clock.advance(1000);
    await answered;
    

Learn more

app/teas/[slug]/page.tsxSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).