Skip to the code

A page for every tea

Leaf and Kettle wants a page for each tea, at /teas/green, /teas/mint, and so on. Write app/teas/[slug]/page.tsx. Its default export is the page: an async Server Component that Next.js gives params, a promise of { slug }.

Load the tea with getTea(slug) from @/lib/teas. When there's no such tea, call notFound() from next/navigation, so the visitor gets the 404 page.

Show the tea's name in an <h1>, its price with two decimals and a dollar sign ($4.00), its about text, and its stock: In stock: 12, or Sold out when stock is 0.

Also export generateStaticParams, which returns { slug } for every tea getTeas() gives, in the shop's order, so next build makes every tea's page ahead of time.

/teas/mint → Mint tea, $3.00, Cool and sweet., In stock: 12
/teas/coffee → 404

The app's other files

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

export type Tea = { slug: string; name: string; price: number; about: string; stock: number };
 
const teas: Tea[] = [
  { slug: "green", name: "Green tea", price: 4, about: "Light and fresh.", stock: 30 },
  { slug: "mint", name: "Mint tea", price: 3, about: "Cool and sweet.", stock: 12 },
  { slug: "oolong", name: "Oolong tea", price: 5.5, about: "Rich and smooth.", stock: 0 },
];
 
/** Every tea, in the shop's order. */
export async function getTeas(): Promise<Tea[]> {
  return teas;
}
 
/** The tea with this slug, or undefined when the shop doesn't sell it. */
export async function getTea(slug: string): Promise<Tea | undefined> {
  return teas.find((tea) => tea.slug === slug);
}

What the tests check

  1. shows the tea's name, price, and description
    await renderServer(<Page params={params({ slug: "green" })} />);
    expect(screen.getByRole("heading", { level: 1, name: "Green tea" })).toBeInTheDocument();
    expect(screen.getByText("$4.00")).toBeInTheDocument();
    expect(screen.getByText("Light and fresh.")).toBeInTheDocument();
    
  2. shows prices with two decimals, and the stock or Sold out
    await renderServer(<Page params={params({ slug: "mint" })} />);
    expect(screen.getByText("In stock: 12")).toBeInTheDocument();
    cleanup();
    await renderServer(<Page params={params({ slug: "oolong" })} />);
    expect(screen.getByText("$5.50")).toBeInTheDocument();
    expect(screen.getByText("Sold out")).toBeInTheDocument();
    expect(screen.queryByText(/In stock/)).not.toBeInTheDocument();
    
  3. calls notFound() for a tea the shop doesn't sell
    expect(await accessErrorOf(() => renderServer(<Page params={params({ slug: "coffee" })} />))).toBe(404);
    
  4. generateStaticParams lists every tea's slug
    expect(await generateStaticParams()).toEqual([{ slug: "green" }, { slug: "mint" }, { slug: "oolong" }]);
    

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).