Skip to the code

A poll you can vote in once

Leaf and Kettle asks its customers to pick the autumn special. Write the poll page, app/poll/page.tsx, a Server Component. poll from @/lib/poll has the poll's id, its question, and its options, each { id, label }; getVotes() answers each option's votes by id, and recordVote(optionId) adds one.

Show the question in an <h1>. A browser that has voted carries a cookie named poll-<poll id>, poll-autumn-special, whose value is the id of the option it voted for. Read it with cookies() from next/headers. Only a value that's one of the poll's option ids counts as a vote.

Without a vote, show a form: a fieldset with the legend Your vote, a radio for each option (named option, its value the option's id, labelled with its label), and a Vote button. Its Server Action does nothing if the cookie already holds a vote, or if option isn't one of the poll's ids. Otherwise it records the vote and sets the cookie for 30 days (maxAge is in seconds), httpOnly, with sameSite: "lax" and path: "/poll".

With a vote, show the results instead of the form: a list with an item for each option, in the poll's order, like Genmaicha: 38% (8 votes), its share of all the votes rounded to a whole percent, 1 vote for one, and , your vote after the option this browser chose. Under it, the total, like 21 votes in all. Setting a cookie in a Server Action makes Next.js render the page again in the same response, so the voter sees the results at once.

No cookie → Which tea should be our autumn special?
            Your vote: ( ) Masala chai  ( ) Genmaicha  ( ) Vanilla rooibos  [Vote]
 
Vote for Genmaicha → recordVote("genmaicha")
  Set-Cookie: poll-autumn-special=genmaicha; Path=/poll; Max-Age=2592000; HttpOnly; SameSite=lax
→ Masala chai: 43% (9 votes)
  Genmaicha: 38% (8 votes), your vote
  Vanilla rooibos: 19% (4 votes)
  21 votes in all

The app's other files

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

export type PollOption = { id: string; label: string };
 
/** This month's poll. */
export const poll = {
  id: "autumn-special",
  question: "Which tea should be our autumn special?",
  options: [
    { id: "chai", label: "Masala chai" },
    { id: "genmaicha", label: "Genmaicha" },
    { id: "rooibos", label: "Vanilla rooibos" },
  ] as PollOption[],
};
 
/** Each option's votes so far: a stand-in for the shop's database. */
export const votes: Record<string, number> = { chai: 9, genmaicha: 7, rooibos: 4 };
 
export async function getVotes(): Promise<Record<string, number>> {
  return { ...votes };
}
 
/** Adds one vote for the option with this id, which must be one of the poll's. */
export async function recordVote(optionId: string) {
  votes[optionId] += 1;
}

What the tests check

  1. asks the question, with a radio for each option, until you've voted
    await renderServer(<Page />);
    expect(screen.getByRole("heading", { level: 1, name: "Which tea should be our autumn special?" })).toBeInTheDocument();
    expect(screen.getByRole("group", { name: "Your vote" })).toBeInTheDocument();
    expect(screen.getAllByRole("radio").map((radio) => radio.value)).toEqual(["chai", "genmaicha", "rooibos"]);
    expect(screen.getByRole("radio", { name: "Vanilla rooibos" })).not.toBeChecked();
    expect(screen.getByRole("button", { name: "Vote" })).toBeInTheDocument();
    expect(screen.queryByText(/votes in all/)).not.toBeInTheDocument();
    
  2. a vote is counted and remembered in a cookie, and the results show
    const COOKIE = "poll-autumn-special";
    const results = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const vote = async (label) => {
      if (label) await user.click(screen.getByRole("radio", { name: label }));
      await user.click(screen.getByRole("button", { name: "Vote" }));
      await flush();
    };
    const voteAction = async (element) => {
      let found = null;
      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 = 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 vote form has no Server Action as its action.");
      return found;
    };
    await withRequest({}, async (request) => {
      await renderServer(<Page />);
      await vote("Genmaicha");
      expect(votes).toEqual({ chai: 9, genmaicha: 8, rooibos: 4 });
      expect(request.setCookies.map(({ name, value, httpOnly, sameSite, path, maxAge }) => ({ name, value, httpOnly, sameSite, path, maxAge }))).toEqual([
        { name: COOKIE, value: "genmaicha", httpOnly: true, sameSite: "lax", path: "/poll", maxAge: 2592000 },
      ]);
      // Next.js renders the page again in the same response, with the new cookie.
      cleanup();
      await renderServer(<Page />);
      expect(results()).toEqual(["Masala chai: 43% (9 votes)", "Genmaicha: 38% (8 votes), your vote", "Vanilla rooibos: 19% (4 votes)"]);
      expect(screen.getByText("21 votes in all")).toBeInTheDocument();
      expect(screen.queryByRole("button", { name: "Vote" })).not.toBeInTheDocument();
    });
    
  3. shows a voter the rounded shares, with one vote as 1 vote
    const COOKIE = "poll-autumn-special";
    const results = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const vote = async (label) => {
      if (label) await user.click(screen.getByRole("radio", { name: label }));
      await user.click(screen.getByRole("button", { name: "Vote" }));
      await flush();
    };
    const voteAction = async (element) => {
      let found = null;
      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 = 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 vote form has no Server Action as its action.");
      return found;
    };
    votes.rooibos = 1;
    await withRequest({ cookies: { [COOKIE]: "rooibos" } }, () => renderServer(<Page />));
    expect(results()).toEqual(["Masala chai: 53% (9 votes)", "Genmaicha: 41% (7 votes)", "Vanilla rooibos: 6% (1 vote), your vote"]);
    expect(screen.getByText("17 votes in all")).toBeInTheDocument();
    expect(screen.queryByRole("radio")).not.toBeInTheDocument();
    
  4. a second vote from the same browser counts for nothing
    const COOKIE = "poll-autumn-special";
    const results = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const vote = async (label) => {
      if (label) await user.click(screen.getByRole("radio", { name: label }));
      await user.click(screen.getByRole("button", { name: "Vote" }));
      await flush();
    };
    const voteAction = async (element) => {
      let found = null;
      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 = 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 vote form has no Server Action as its action.");
      return found;
    };
    await withRequest({}, async (request) => {
      await renderServer(<Page />);
      await vote("Masala chai");
      // The form is still on screen, as in a second tab: vote again.
      await vote("Vanilla rooibos");
      expect(votes).toEqual({ chai: 10, genmaicha: 7, rooibos: 4 });
      expect(request.setCookies.map((cookie) => cookie.value)).toEqual(["chai"]);
    });
    // A form from before this browser voted, sent with the cookie it has now.
    const oldForm = await withRequest({}, () => voteAction(<Page />));
    await withRequest({ kind: "action", cookies: { [COOKIE]: "genmaicha" } }, async (request) => {
      await oldForm(formData({ option: "rooibos" }));
      expect(votes).toEqual({ chai: 10, genmaicha: 7, rooibos: 4 });
      expect(request.setCookies).toEqual([]);
    });
    
  5. ignores a vote for nothing, or for an option the poll doesn't have
    const COOKIE = "poll-autumn-special";
    const results = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const vote = async (label) => {
      if (label) await user.click(screen.getByRole("radio", { name: label }));
      await user.click(screen.getByRole("button", { name: "Vote" }));
      await flush();
    };
    const voteAction = async (element) => {
      let found = null;
      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 = 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 vote form has no Server Action as its action.");
      return found;
    };
    await withRequest({}, async (request) => {
      await renderServer(<Page />);
      await vote(null);
      const action = await voteAction(<Page />);
      await action(formData({ option: "coffee" }));
      await action(formData({ option: "constructor" }));
      expect(votes).toEqual({ chai: 9, genmaicha: 7, rooibos: 4 });
      expect(request.setCookies).toEqual([]);
    });
    
  6. a cookie that names no option still gets the vote form
    const COOKIE = "poll-autumn-special";
    const results = () => screen.getAllByRole("listitem").map((item) => item.textContent);
    const vote = async (label) => {
      if (label) await user.click(screen.getByRole("radio", { name: label }));
      await user.click(screen.getByRole("button", { name: "Vote" }));
      await flush();
    };
    const voteAction = async (element) => {
      let found = null;
      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 = 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 vote form has no Server Action as its action.");
      return found;
    };
    await withRequest({ cookies: { [COOKIE]: "coffee" } }, async (request) => {
      await renderServer(<Page />);
      expect(screen.getAllByRole("radio")).toHaveLength(3);
      await vote("Vanilla rooibos");
      expect(votes.rooibos).toBe(5);
      expect(request.setCookies.map((cookie) => cookie.value)).toEqual(["rooibos"]);
    });
    

Learn more

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