Skip to the code

Move the tea list back to the server

Leaf and Kettle's tea list, app/teas/page.tsx, was written as one big Client Component: it starts with "use client", shows Loading teas…, and fetches /api/teas in an effect once it's in the browser. Only the Add to cart buttons need the browser. Make the page a Server Component again: an async function that loads the teas with getTeas() from @/lib/teas, so they're in the first HTML, with no loading state and no request from the browser.

Keep the buttons working with AddToCartButton from ./add-to-cart-button. That file starts with "use client", so it stays a Client Component when a Server Component renders it, and it calls the addToCart Server Action when clicked. Give it the tea's slug and name.

Render an <h1> with Our teas, then a list with an item for each tea, in the shop's order: its name in an <h2>, its price with two decimals ($5.50), and the button, or the text Sold out instead of a button when its stock is 0.

<h1>Our teas</h1>
<ul>
  <li><h2>Green tea</h2> <p>$4.00</p> <AddToCartButton slug="green" name="Green tea" /></li>
  <li><h2>Oolong tea</h2> <p>$5.50</p> <p>Sold out</p></li>
  …
</ul>

The app's other files

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

import "server-only";
 
export type Tea = { slug: string; name: string; price: number; stock: number };
 
const teas: Tea[] = [
  { slug: "green", name: "Green tea", price: 4, stock: 30 },
  { slug: "mint", name: "Mint tea", price: 3, stock: 12 },
  { slug: "oolong", name: "Oolong tea", price: 5.5, stock: 0 },
  { slug: "jasmine", name: "Jasmine green tea", price: 5, stock: 7 },
];
 
/** Every tea, in the shop's order. It reads the shop's database, so only the server can call it. */
export async function getTeas(): Promise<Tea[]> {
  return teas;
}

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

/** The slug of every tea added to the visitor's cart, in order. A real shop keeps the cart in its database. */
export const cart: string[] = [];

app/actions.ts, read-only. Import it as @/app/actions.

"use server";
 
import { cart } from "@/lib/cart";
 
/** Adds one of the tea to the visitor's cart. */
export async function addToCart(slug: string) {
  cart.push(slug);
}

app/teas/add-to-cart-button.tsx, read-only. Import it as @/app/teas/add-to-cart-button.

"use client";
 
import { useState, useTransition } from "react";
import { addToCart } from "@/app/actions";
 
export default function AddToCartButton({ slug, name }: { slug: string; name: string }) {
  const [added, setAdded] = useState(false);
  const [pending, startTransition] = useTransition();
 
  return (
    <button
      type="button"
      aria-label={`Add ${name} to cart`}
      disabled={pending}
      onClick={() =>
        startTransition(async () => {
          await addToCart(slug);
          setAdded(true);
        })
      }
    >
      {added ? "Added" : "Add to cart"}
    </button>
  );
}

What the tests check

  1. lists every tea in the first render, with no loading state
    await renderServer(<Page />);
    expect(screen.getByRole("heading", { level: 1, name: "Our teas" })).toBeInTheDocument();
    expect(screen.getAllByRole("heading", { level: 2 }).map((heading) => heading.textContent)).toEqual(["Green tea", "Mint tea", "Oolong tea", "Jasmine green tea"]);
    expect(screen.queryByText("Loading teas…")).not.toBeInTheDocument();
    
  2. is a Server Component: Next.js can call it and await it, with no hooks
    const callAsServerComponent = async () => {
      try {
        return await Page({ params: params({}), searchParams: params({}) });
      } catch (error) {
        throw new Error("Next.js calls a Server Component as a plain async function on the server, where hooks don't work, and it threw: " + error.message);
      }
    };
    const page = await callAsServerComponent();
    expect(React.isValidElement(page)).toBe(true);
    
  3. shows each price with two decimals
    await renderServer(<Page />);
    const prices = screen.getAllByRole("listitem").map((item) => item.textContent.match(/\$\d+\.\d\d/)?.[0]);
    expect(prices).toEqual(["$4.00", "$3.00", "$5.50", "$5.00"]);
    
  4. gives in-stock teas an Add to cart button, and sold-out ones Sold out
    await renderServer(<Page />);
    expect(screen.getAllByRole("button").map((button) => button.getAttribute("aria-label"))).toEqual(["Add Green tea to cart", "Add Mint tea to cart", "Add Jasmine green tea to cart"]);
    const oolong = screen.getAllByRole("listitem")[2];
    expect(within(oolong).getByText("Sold out")).toBeInTheDocument();
    expect(within(oolong).queryByRole("button")).toBeNull();
    
  5. the buttons still work: a click runs the addToCart Server Action
    await renderServer(<Page />);
    await user.click(screen.getByRole("button", { name: "Add Mint tea to cart" }));
    await flush();
    expect(cart).toEqual(["mint"]);
    expect(screen.getByRole("button", { name: "Add Mint tea to cart" })).toHaveTextContent("Added");
    
  6. the browser never asks for the teas
    const api = mockFetch(() => json([]));
    await renderServer(<Page />);
    await flush();
    expect(api.calls).toEqual([]);
    

Learn more

app/teas/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).