Skip to the code

Remove buttons bound to each tea

The wishlist page at Leaf and Kettle, /wishlist, lists the teas a customer has saved for later, each with a Remove button. Write it, app/wishlist/page.tsx, an async Server Component.

Render an <h1> with Your wishlist. Then, for each tea from getWishlist() in @/lib/wishlist, a list item with the tea's name and a form with one button, Remove, labelled for screen readers with the tea it removes, like aria-label="Remove Mint tea". When the wishlist is empty, show a paragraph, Your wishlist is empty., and no list.

Write the Server Action in the page: an async function removeTea(slug: string) whose body starts with "use server". It takes the tea off with removeFromWishlist(slug), then calls revalidatePath("/wishlist"), so Next.js renders the page again without it and sends it back in the same response.

The forms have no fields. Give each one its own copy of the action with the slug filled in, removeTea.bind(null, item.slug). A bound Server Action carries its arguments with it: when the form is sent, the action gets the slug first, then the form's FormData.

Wishlist: green, mint, oolong
→ <h1>Your wishlist</h1>
  Green tea  [Remove]   (aria-label "Remove Green tea")
  Mint tea   [Remove]
  Oolong tea [Remove]
 
Remove Mint tea → removeTea("mint", formData) → revalidatePath("/wishlist")

The app's other files

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

export type WishlistItem = { slug: string; name: string };
 
/** The signed-in customer's wishlist: a stand-in for the shop's database. */
export const wishlist: WishlistItem[] = [
  { slug: "green", name: "Green tea" },
  { slug: "mint", name: "Mint tea" },
  { slug: "oolong", name: "Oolong tea" },
];
 
export async function getWishlist(): Promise<WishlistItem[]> {
  return wishlist.map((item) => ({ ...item }));
}
 
/** Takes the tea with this slug off the wishlist. A slug that isn't on it changes nothing. */
export async function removeFromWishlist(slug: string) {
  const index = wishlist.findIndex((item) => item.slug === slug);
  if (index !== -1) wishlist.splice(index, 1);
}

What the tests check

  1. lists each tea with its own Remove button
    await renderServer(<Page />);
    expect(screen.getByRole("heading", { level: 1, name: "Your wishlist" })).toBeInTheDocument();
    const items = screen.getAllByRole("listitem");
    expect(items).toHaveLength(3);
    ["Green tea", "Mint tea", "Oolong tea"].forEach((name, index) => {
      expect(items[index]).toHaveTextContent(name);
      expect(within(items[index]).getByRole("button", { name: "Remove " + name })).toHaveTextContent("Remove");
    });
    
  2. Remove takes that tea off and revalidates the wishlist page
    const formActions = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === "form") found.push(node.props.action);
          if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    const slugs = () => wishlist.map((item) => item.slug);
    await renderServer(<Page />);
    await user.click(screen.getByRole("button", { name: "Remove Mint tea" }));
    await flush();
    expect(slugs()).toEqual(["green", "oolong"]);
    expect(cache.revalidatedPaths).toEqual(["/wishlist"]);
    // Next.js renders the page again, and sends it back with the action's answer.
    cleanup();
    await renderServer(<Page />);
    expect(screen.queryByRole("button", { name: "Remove Mint tea" })).not.toBeInTheDocument();
    expect(screen.getAllByRole("listitem")).toHaveLength(2);
    
  3. each form's action already holds its tea's slug, so the form needs no fields
    const formActions = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === "form") found.push(node.props.action);
          if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    const slugs = () => wishlist.map((item) => item.slug);
    const actions = await formActions(<Page />);
    expect(actions).toHaveLength(3);
    await actions[2](new FormData());
    expect(slugs()).toEqual(["green", "mint"]);
    await actions[0](new FormData());
    expect(slugs()).toEqual(["mint"]);
    
  4. removing every tea leaves the empty message and no list
    const formActions = async (element) => {
      const found = [];
      const visit = async (node) => {
        if (Array.isArray(node)) {
          for (const item of node) await visit(item);
        } else if (React.isValidElement(node)) {
          if (node.type === "form") found.push(node.props.action);
          if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      return found;
    };
    const slugs = () => wishlist.map((item) => item.slug);
    await renderServer(<Page />);
    for (const name of ["Green tea", "Mint tea", "Oolong tea"]) {
      await user.click(screen.getByRole("button", { name: "Remove " + name }));
      await flush();
    }
    expect(slugs()).toEqual([]);
    cleanup();
    await renderServer(<Page />);
    expect(screen.getByText("Your wishlist is empty.")).toBeInTheDocument();
    expect(screen.queryByRole("list")).not.toBeInTheDocument();
    expect(screen.queryByRole("button")).not.toBeInTheDocument();
    

Learn more

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