Skip to the code

A task list for the shop floor

Leaf and Kettle's staff keep the day's jobs on a list at /tasks: restock the mint, descale the kettle, write the specials board. Write the page, app/tasks/page.tsx, an async Server Component that reads the tasks with getTasks() from @/lib/tasks and changes them through Server Actions written in the page itself, so the whole list works with plain forms.

Render an <h1> with Today's tasks, then a form to add a task: a text field labelled New task, named title, and an Add button. Its Server Action trims the title and saves it with createTask(title). A missing or blank title, or one longer than 80 characters, adds nothing: the action checks, whatever the field allows.

Below the form, show how many tasks are done, like 1 of 3 done, then a list with an item for each task, in order: its title, inside <s> when it's done; a Done button labelled Mark <title> as done, or for a done task an Undo button labelled Mark <title> as not done; and a Delete button labelled Delete <title>. With no tasks, show Nothing to do. Put the kettle on. in place of the count and the list.

Done calls setDone(id, true), Undo calls setDone(id, false), and Delete calls deleteTask(id). Each button sends what it wants, not "flip it": a second Done sent from a page that hasn't caught up yet leaves the task done. Every action that changes a task then calls revalidatePath("/tasks"), so Next.js sends the page back, fresh, with the action's answer.

Today's tasks
New task [                    ] [Add]
1 of 3 done
  Restock the mint tea       [Done] [Delete]
  Descale the big kettle     [Undo] [Delete]    (in <s>, labelled "Mark Descale the big kettle as not done")
  Write the specials board   [Done] [Delete]
 
Done on "Restock the mint tea" → setDone("t1", true) → revalidatePath("/tasks")

The app's other files

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

export type Task = { id: string; title: string; done: boolean };
 
/** Today's tasks, in order: a stand-in for the shop's database. */
export const tasks: Task[] = [
  { id: "t1", title: "Restock the mint tea", done: false },
  { id: "t2", title: "Descale the big kettle", done: true },
  { id: "t3", title: "Write the specials board", done: false },
];
let lastId = 3;
 
export async function getTasks(): Promise<Task[]> {
  return tasks.map((task) => ({ ...task }));
}
 
/** Adds a task, not done yet, to the end of the list. */
export async function createTask(title: string): Promise<Task> {
  lastId += 1;
  const task = { id: `t${lastId}`, title, done: false };
  tasks.push(task);
  return { ...task };
}
 
/** Marks the task done (true) or not done (false). An id that isn't on the list changes nothing. */
export async function setDone(id: string, done: boolean) {
  const task = tasks.find((entry) => entry.id === id);
  if (task) task.done = done;
}
 
/** Deletes the task. An id that isn't on the list changes nothing. */
export async function deleteTask(id: string) {
  const index = tasks.findIndex((entry) => entry.id === id);
  if (index !== -1) tasks.splice(index, 1);
}

What the tests check

  1. lists the tasks with their buttons and how many are done
    await renderServer(<Page />);
    expect(screen.getByRole("heading", { level: 1, name: "Today's tasks" })).toBeInTheDocument();
    expect(screen.getByText("1 of 3 done")).toBeInTheDocument();
    const [mint, kettle, board] = screen.getAllByRole("listitem");
    expect(within(mint).getByRole("button", { name: "Mark Restock the mint tea as done" })).toHaveTextContent("Done");
    expect(within(kettle).getByRole("button", { name: "Mark Descale the big kettle as not done" })).toHaveTextContent("Undo");
    expect(within(kettle).getByText("Descale the big kettle").tagName).toBe("S");
    expect(within(mint).getByText("Restock the mint tea").tagName).not.toBe("S");
    expect(within(board).getByRole("button", { name: "Delete Write the specials board" })).toHaveTextContent("Delete");
    
  2. Add saves the trimmed title and revalidates /tasks
    const titles = () => tasks.map((task) => task.title);
    const click = async (name) => {
      await user.click(screen.getByRole("button", { name }));
      await flush();
    };
    // After a Server Action that revalidates, Next.js renders the page again and sends it back.
    const reopen = async () => {
      cleanup();
      await renderServer(<Page />);
    };
    const addAction = async (element) => {
      let found = null;
      const hasTitleField = (node) =>
        Array.isArray(node) ? node.some(hasTitleField) : React.isValidElement(node) && ((node.type === "input" && node.props.name === "title") || hasTitleField(node.props.children));
      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" && hasTitleField(node.props.children)) found = node.props.action;
          if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      if (typeof found !== "function") throw new Error("The form with the title field has no Server Action as its action.");
      return found;
    };
    await renderServer(<Page />);
    await user.type(screen.getByLabelText("New task"), "  Rinse the teapots  ");
    await click("Add");
    expect(titles()).toEqual(["Restock the mint tea", "Descale the big kettle", "Write the specials board", "Rinse the teapots"]);
    expect(tasks[3].done).toBe(false);
    expect(cache.revalidatedPaths).toEqual(["/tasks"]);
    await reopen();
    expect(screen.getByText("1 of 4 done")).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Mark Rinse the teapots as done" })).toBeInTheDocument();
    
  3. a missing, blank, or overlong title adds nothing
    const titles = () => tasks.map((task) => task.title);
    const click = async (name) => {
      await user.click(screen.getByRole("button", { name }));
      await flush();
    };
    // After a Server Action that revalidates, Next.js renders the page again and sends it back.
    const reopen = async () => {
      cleanup();
      await renderServer(<Page />);
    };
    const addAction = async (element) => {
      let found = null;
      const hasTitleField = (node) =>
        Array.isArray(node) ? node.some(hasTitleField) : React.isValidElement(node) && ((node.type === "input" && node.props.name === "title") || hasTitleField(node.props.children));
      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" && hasTitleField(node.props.children)) found = node.props.action;
          if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      if (typeof found !== "function") throw new Error("The form with the title field has no Server Action as its action.");
      return found;
    };
    await renderServer(<Page />);
    await user.type(screen.getByLabelText("New task"), "   ");
    await click("Add");
    const add = await addAction(<Page />);
    await add(formData({}));
    await add(formData({ title: "   " }));
    await add(formData({ title: "x".repeat(81) }));
    expect(titles()).toEqual(["Restock the mint tea", "Descale the big kettle", "Write the specials board"]);
    await add(formData({ title: "y".repeat(80) }));
    expect(titles()).toHaveLength(4);
    
  4. Done and Undo mark a task done and not done, and revalidate /tasks
    const titles = () => tasks.map((task) => task.title);
    const click = async (name) => {
      await user.click(screen.getByRole("button", { name }));
      await flush();
    };
    // After a Server Action that revalidates, Next.js renders the page again and sends it back.
    const reopen = async () => {
      cleanup();
      await renderServer(<Page />);
    };
    const addAction = async (element) => {
      let found = null;
      const hasTitleField = (node) =>
        Array.isArray(node) ? node.some(hasTitleField) : React.isValidElement(node) && ((node.type === "input" && node.props.name === "title") || hasTitleField(node.props.children));
      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" && hasTitleField(node.props.children)) found = node.props.action;
          if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      if (typeof found !== "function") throw new Error("The form with the title field has no Server Action as its action.");
      return found;
    };
    await renderServer(<Page />);
    await click("Mark Restock the mint tea as done");
    expect(tasks[0].done).toBe(true);
    expect(cache.revalidatedPaths).toEqual(["/tasks"]);
    await reopen();
    expect(screen.getByText("2 of 3 done")).toBeInTheDocument();
    expect(screen.getByText("Restock the mint tea").tagName).toBe("S");
    await click("Mark Descale the big kettle as not done");
    expect(tasks[1].done).toBe(false);
    await reopen();
    expect(screen.getByRole("button", { name: "Mark Descale the big kettle as done" })).toHaveTextContent("Done");
    expect(screen.getByText("1 of 3 done")).toBeInTheDocument();
    
  5. a second Done from a page that hasn't caught up leaves the task done
    const titles = () => tasks.map((task) => task.title);
    const click = async (name) => {
      await user.click(screen.getByRole("button", { name }));
      await flush();
    };
    // After a Server Action that revalidates, Next.js renders the page again and sends it back.
    const reopen = async () => {
      cleanup();
      await renderServer(<Page />);
    };
    const addAction = async (element) => {
      let found = null;
      const hasTitleField = (node) =>
        Array.isArray(node) ? node.some(hasTitleField) : React.isValidElement(node) && ((node.type === "input" && node.props.name === "title") || hasTitleField(node.props.children));
      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" && hasTitleField(node.props.children)) found = node.props.action;
          if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      if (typeof found !== "function") throw new Error("The form with the title field has no Server Action as its action.");
      return found;
    };
    await renderServer(<Page />);
    await click("Mark Restock the mint tea as done");
    // The page on screen is the one from before the first click: the same form is sent again.
    await click("Mark Restock the mint tea as done");
    expect(tasks[0].done).toBe(true);
    await click("Mark Descale the big kettle as not done");
    await click("Mark Descale the big kettle as not done");
    expect(tasks[1].done).toBe(false);
    
  6. Delete removes the task, and an empty list shows the message
    const titles = () => tasks.map((task) => task.title);
    const click = async (name) => {
      await user.click(screen.getByRole("button", { name }));
      await flush();
    };
    // After a Server Action that revalidates, Next.js renders the page again and sends it back.
    const reopen = async () => {
      cleanup();
      await renderServer(<Page />);
    };
    const addAction = async (element) => {
      let found = null;
      const hasTitleField = (node) =>
        Array.isArray(node) ? node.some(hasTitleField) : React.isValidElement(node) && ((node.type === "input" && node.props.name === "title") || hasTitleField(node.props.children));
      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" && hasTitleField(node.props.children)) found = node.props.action;
          if (typeof node.type === "function") await visit(await node.type(node.props));
          else await visit(node.props.children);
        }
      };
      await visit(element);
      if (typeof found !== "function") throw new Error("The form with the title field has no Server Action as its action.");
      return found;
    };
    await renderServer(<Page />);
    await click("Delete Descale the big kettle");
    expect(titles()).toEqual(["Restock the mint tea", "Write the specials board"]);
    expect(cache.revalidatedPaths).toEqual(["/tasks"]);
    await reopen();
    expect(screen.getAllByRole("listitem")).toHaveLength(2);
    await click("Delete Restock the mint tea");
    await click("Delete Write the specials board");
    await reopen();
    expect(screen.getByText("Nothing to do. Put the kettle on.")).toBeInTheDocument();
    expect(screen.queryByRole("list")).not.toBeInTheDocument();
    expect(screen.queryByText(/of \d+ done/)).not.toBeInTheDocument();
    expect(screen.getByLabelText("New task")).toBeInTheDocument();
    

Learn more

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