Skip to the code

An Add to cart form that shows it's working

The Add to cart form on each tea's page at Leaf and Kettle calls addToCart, a Server Action in app/actions.ts, and the shop's database takes half a second to answer. Write the form, app/teas/[slug]/add-to-cart-form.tsx, a Client Component whose default export is AddToCartForm({ slug }). The tea's page, a Server Component, renders it with the tea's slug.

A Client Component can't define a Server Action, but it can import one from a file that starts with "use server". Use addToCart as the form's action through React's useActionState, which gives you the action's last answer and whether it's still running. addToCart(previous, formData) reads two fields, slug and quantity, and answers { ok, message }.

The form has a hidden slug field, a number field labelled Quantity, named quantity, that starts at 1, and a submit button, Add to cart.

While the action runs, the button reads Adding… and is disabled, so a second click can't add the tea twice.

Show the answer's message under the button, in an element with role="status" when ok is true, and with role="alert" when it's false. A new answer replaces the last one.

Quantity 2, Add to cart
→ [Adding…] (disabled), then half a second later:
→ [Add to cart]  Added 2 × Green tea to your cart.   (role="status")
 
Quantity 5 of oolong, which has 3 left
→ Only 3 left.   (role="alert")

The app's other files

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

export type Tea = { slug: string; name: string; stock: number };
 
const teas: Tea[] = [
  { slug: "green", name: "Green tea", stock: 30 },
  { slug: "mint", name: "Mint tea", stock: 12 },
  { slug: "oolong", name: "Oolong tea", stock: 3 },
];
 
/** 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);
}

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

export type CartLine = { slug: string; quantity: number };
 
/** What's in the visitor's cart, one line per Add to cart. A real shop keeps it in its database. */
export const cart: CartLine[] = [];

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

"use server";
 
import { cart } from "@/lib/cart";
import { getTea } from "@/lib/teas";
 
export type CartState = { ok: boolean; message: string } | null;
 
/** How long the shop's database takes to save. */
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
 
/** Adds `quantity` of the tea `slug` to the cart, and says what happened. Takes half a second. */
export async function addToCart(previous: CartState, formData: FormData): Promise<CartState> {
  await wait(500);
  const tea = await getTea(String(formData.get("slug")));
  const quantity = Number(formData.get("quantity"));
  if (!tea) return { ok: false, message: "We don't sell that tea." };
  if (!Number.isInteger(quantity) || quantity < 1) return { ok: false, message: "Choose at least 1." };
  if (quantity > tea.stock) return { ok: false, message: `Only ${tea.stock} left.` };
  cart.push({ slug: tea.slug, quantity });
  return { ok: true, message: `Added ${quantity} × ${tea.name} to your cart.` };
}

app/teas/[slug]/page.tsx, read-only. Import it as @/app/teas/[slug]/page.

import { notFound } from "next/navigation";
import { getTea } from "@/lib/teas";
import AddToCartForm from "./add-to-cart-form";
 
export default async function TeaPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const tea = await getTea(slug);
  if (!tea) notFound();
 
  return (
    <main>
      <h1>{tea.name}</h1>
      <AddToCartForm slug={tea.slug} />
    </main>
  );
}

What the tests check

  1. is a Client Component the tea's page can render
    const renderOnServer = async (element, options) => {
      try {
        return await renderServer(element, options);
      } catch (error) {
        if (/reading 'use[A-Za-z]*'/.test(String(error && error.message))) {
          throw new Error('A component that calls hooks ran as a Server Component, where there are none. Does its file start with "use client"? (' + error.message + ")");
        }
        throw error;
      }
    };
    await renderOnServer(<Page params={params({ slug: "green" })} />);
    expect(screen.getByRole("heading", { level: 1, name: "Green tea" })).toBeInTheDocument();
    expect(screen.getByLabelText("Quantity")).toHaveValue(1);
    expect(screen.getByRole("button", { name: "Add to cart" })).toBeEnabled();
    
  2. sends the slug and the quantity, then shows the answer
    const send = async (quantity) => {
      await user.clear(screen.getByLabelText("Quantity"));
      await user.type(screen.getByLabelText("Quantity"), String(quantity));
      await user.click(screen.getByRole("button", { name: "Add to cart" }));
    };
    const clock = useFakeTimers();
    await renderServer(<Page params={params({ slug: "green" })} />);
    await send(2);
    await clock.advance(500);
    expect(cart).toEqual([{ slug: "green", quantity: 2 }]);
    expect(screen.getByRole("status")).toHaveTextContent("Added 2 × Green tea to your cart.");
    
  3. shows Adding… on a disabled button while the action runs
    const clock = useFakeTimers();
    render(<AddToCartForm slug="mint" />);
    await user.click(screen.getByRole("button", { name: "Add to cart" }));
    await flush();
    expect(screen.getByRole("button", { name: "Adding…" })).toBeDisabled();
    await user.click(screen.getByRole("button", { name: "Adding…" }));
    await clock.advance(1000);
    expect(screen.getByRole("button", { name: "Add to cart" })).toBeEnabled();
    expect(cart).toEqual([{ slug: "mint", quantity: 1 }]);
    
  4. shows the action's error in an alert, and adds nothing
    const send = async (quantity) => {
      await user.clear(screen.getByLabelText("Quantity"));
      await user.type(screen.getByLabelText("Quantity"), String(quantity));
      await user.click(screen.getByRole("button", { name: "Add to cart" }));
    };
    const clock = useFakeTimers();
    render(<AddToCartForm slug="oolong" />);
    await send(5);
    await clock.advance(500);
    expect(screen.getByRole("alert")).toHaveTextContent("Only 3 left.");
    expect(screen.queryByText(/Added/)).not.toBeInTheDocument();
    expect(cart).toEqual([]);
    
  5. a new answer replaces the last one
    const send = async (quantity) => {
      await user.clear(screen.getByLabelText("Quantity"));
      await user.type(screen.getByLabelText("Quantity"), String(quantity));
      await user.click(screen.getByRole("button", { name: "Add to cart" }));
    };
    const clock = useFakeTimers();
    render(<AddToCartForm slug="oolong" />);
    await send(5);
    await clock.advance(500);
    expect(screen.getByRole("alert")).toHaveTextContent("Only 3 left.");
    await send(3);
    await clock.advance(500);
    expect(screen.getByRole("status")).toHaveTextContent("Added 3 × Oolong tea to your cart.");
    expect(screen.queryByText("Only 3 left.")).not.toBeInTheDocument();
    expect(cart).toEqual([{ slug: "oolong", quantity: 3 }]);
    

Learn more

app/teas/[slug]/add-to-cart-form.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).