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>
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>
);
}
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();
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);
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"]);
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();
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");
const api = mockFetch(() => json([]));
await renderServer(<Page />);
await flush();
expect(api.calls).toEqual([]);
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).
I'm here to help with Move the tea list back to the server. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.