Skip to the code

A newsletter form that keeps what was typed

The Leaf and Kettle letter has a sign-up form at /newsletter. Its Server Action, subscribe in app/actions.ts, is written: it checks the fields and answers with a SubscribeState from @/lib/newsletter, which has a status, a message, errors with a message for each wrong field, and values, what the form sent. Write the form, app/newsletter/newsletter-form.tsx, a Client Component whose default export is NewsletterForm.

Run subscribe with useActionState, starting from initialSubscribeState, and give its action to <form action>, so the server-rendered form works even before the page's JavaScript has loaded. Add noValidate to the form: the action's checks, some of which only the server can make, give every message.

The form has a text field labelled Name (named name), an email field labelled Email (named email), a fieldset with the legend Topics and three checkboxes named topics, with the values new-teas, brewing-tips, and offers and the labels New teas, Brewing tips, and Offers, and a Subscribe button.

React resets a form after its action finishes, so on its own the form would lose everything typed whenever the server answers with errors. Give each field its value from state.values as its default, defaultValue for the text fields and defaultChecked for the boxes: then the fields show what was sent after an error, and are empty after a sign-up, when values comes back empty.

Show each message in state.errors under its field, in a paragraph with the id name-error, email-error, or topics-error. A field with an error gets aria-invalid="true" and an aria-describedby with that id; for the topics, the fieldset gets the aria-describedby. A field without an error has neither.

Show state.message in a paragraph with role="status" when the status is done, and with role="alert" when it's error.

Name "Ben", Email "ben@example", Brewing tips ticked → Subscribe
→ Check the fields marked below.               (role="alert")
  Name [Ben]  Email [ben@example] (aria-invalid)  [x] Brewing tips
  Enter an email like ana@example.com.         (id="email-error")

The app's other files

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

export type SubscribeState = {
  /** "done" after a sign-up, "error" after a failed try, "idle" before the first. */
  status: "idle" | "error" | "done";
  message: string;
  /** A message for each wrong field. */
  errors: { name?: string; email?: string; topics?: string };
  /** What the form sent, to show again after an error; empty after a sign-up. */
  values: { name: string; email: string; topics: string[] };
};
 
export const initialSubscribeState: SubscribeState = {
  status: "idle",
  message: "",
  errors: {},
  values: { name: "", email: "", topics: [] },
};
 
/** Everyone on the mailing list: a stand-in for the shop's database. */
export const subscribers = [{ name: "Mei", email: "mei@example.com", topics: ["offers"] }];

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

"use server";
 
import { subscribers } from "@/lib/newsletter";
import type { SubscribeState } from "@/lib/newsletter";
 
const TOPICS = ["new-teas", "brewing-tips", "offers"];
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
 
export async function subscribe(previous: SubscribeState, formData: FormData): Promise<SubscribeState> {
  const typedName = String(formData.get("name") ?? "");
  const typedEmail = String(formData.get("email") ?? "");
  const topics = formData.getAll("topics").map(String).filter((topic) => TOPICS.includes(topic));
  const name = typedName.trim();
  const email = typedEmail.trim().toLowerCase();
 
  const errors: SubscribeState["errors"] = {};
  if (!name || name.length > 40) errors.name = "Tell us your name, up to 40 characters.";
  if (!EMAIL.test(email)) errors.email = "Enter an email like ana@example.com.";
  else if (subscribers.some((entry) => entry.email === email)) errors.email = "That email is already on the list.";
  if (topics.length === 0) errors.topics = "Pick at least one topic.";
  if (Object.keys(errors).length > 0) {
    return { status: "error", message: "Check the fields marked below.", errors, values: { name: typedName, email: typedEmail, topics } };
  }
 
  subscribers.push({ name, email, topics });
  return { status: "done", message: `Thanks, ${name}! Check your inbox to confirm.`, errors: {}, values: { name: "", email: "", topics: [] } };
}

app/newsletter/page.tsx, read-only. Import it as @/app/newsletter/page.

import NewsletterForm from "./newsletter-form";
 
export default function NewsletterPage() {
  return (
    <main>
      <h1>The Leaf and Kettle letter</h1>
      <NewsletterForm />
    </main>
  );
}

What the tests check

  1. is a Client Component the newsletter 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 />);
    expect(screen.getByRole("heading", { level: 1, name: "The Leaf and Kettle letter" })).toBeInTheDocument();
    expect(screen.getByLabelText("Name")).toHaveValue("");
    expect(screen.getByLabelText("Email")).toHaveAttribute("type", "email");
    expect(screen.getByRole("group", { name: "Topics" })).toBeInTheDocument();
    for (const topic of ["New teas", "Brewing tips", "Offers"]) expect(screen.getByLabelText(topic)).not.toBeChecked();
    
  2. signs the customer up, thanks them, and empties the form
    const send = async ({ name = "", email = "", topics = [] } = {}) => {
      if (name) await user.type(screen.getByLabelText("Name"), name);
      if (email) await user.type(screen.getByLabelText("Email"), email);
      for (const topic of topics) await user.click(screen.getByLabelText(topic));
      await user.click(screen.getByRole("button", { name: "Subscribe" }));
      await flush();
    };
    const errorOf = (field) => {
      const id = field.getAttribute("aria-describedby");
      return id ? document.getElementById(id)?.textContent : undefined;
    };
    render(<NewsletterForm />);
    await send({ name: "Ana", email: "ana@example.com", topics: ["New teas", "Offers"] });
    expect(screen.getByRole("status")).toHaveTextContent("Thanks, Ana! Check your inbox to confirm.");
    expect(subscribers[1]).toEqual({ name: "Ana", email: "ana@example.com", topics: ["new-teas", "offers"] });
    expect(screen.getByLabelText("Name")).toHaveValue("");
    expect(screen.getByLabelText("Email")).toHaveValue("");
    expect(screen.getByLabelText("Offers")).not.toBeChecked();
    expect(screen.queryByRole("alert")).not.toBeInTheDocument();
    
  3. keeps what was typed and ticked when the server finds a mistake
    const send = async ({ name = "", email = "", topics = [] } = {}) => {
      if (name) await user.type(screen.getByLabelText("Name"), name);
      if (email) await user.type(screen.getByLabelText("Email"), email);
      for (const topic of topics) await user.click(screen.getByLabelText(topic));
      await user.click(screen.getByRole("button", { name: "Subscribe" }));
      await flush();
    };
    const errorOf = (field) => {
      const id = field.getAttribute("aria-describedby");
      return id ? document.getElementById(id)?.textContent : undefined;
    };
    render(<NewsletterForm />);
    await send({ name: "Ben", email: "ben@example", topics: ["Brewing tips"] });
    expect(screen.getByRole("alert")).toHaveTextContent("Check the fields marked below.");
    expect(screen.getByLabelText("Name")).toHaveValue("Ben");
    expect(screen.getByLabelText("Email")).toHaveValue("ben@example");
    expect(screen.getByLabelText("Brewing tips")).toBeChecked();
    expect(screen.getByLabelText("New teas")).not.toBeChecked();
    expect(subscribers).toHaveLength(1);
    
  4. marks each wrong field and says what's wrong under it
    const send = async ({ name = "", email = "", topics = [] } = {}) => {
      if (name) await user.type(screen.getByLabelText("Name"), name);
      if (email) await user.type(screen.getByLabelText("Email"), email);
      for (const topic of topics) await user.click(screen.getByLabelText(topic));
      await user.click(screen.getByRole("button", { name: "Subscribe" }));
      await flush();
    };
    const errorOf = (field) => {
      const id = field.getAttribute("aria-describedby");
      return id ? document.getElementById(id)?.textContent : undefined;
    };
    render(<NewsletterForm />);
    await send({ email: "mei@example.com" });
    const name = screen.getByLabelText("Name");
    const email = screen.getByLabelText("Email");
    expect(name).toHaveAttribute("aria-invalid", "true");
    expect(errorOf(name)).toBe("Tell us your name, up to 40 characters.");
    expect(email).toHaveAttribute("aria-invalid", "true");
    expect(errorOf(email)).toBe("That email is already on the list.");
    expect(errorOf(screen.getByRole("group", { name: "Topics" }))).toBe("Pick at least one topic.");
    expect(email).toHaveValue("mei@example.com");
    
  5. a second try keeps the newer values and drops the fixed error
    const send = async ({ name = "", email = "", topics = [] } = {}) => {
      if (name) await user.type(screen.getByLabelText("Name"), name);
      if (email) await user.type(screen.getByLabelText("Email"), email);
      for (const topic of topics) await user.click(screen.getByLabelText(topic));
      await user.click(screen.getByRole("button", { name: "Subscribe" }));
      await flush();
    };
    const errorOf = (field) => {
      const id = field.getAttribute("aria-describedby");
      return id ? document.getElementById(id)?.textContent : undefined;
    };
    render(<NewsletterForm />);
    await send({ name: "Ben", email: "ben@example" });
    await user.clear(screen.getByLabelText("Email"));
    await send({ email: "ben@example.com" });
    expect(screen.getByLabelText("Name")).toHaveValue("Ben");
    expect(screen.getByLabelText("Email")).toHaveValue("ben@example.com");
    expect(screen.getByLabelText("Email")).not.toHaveAttribute("aria-invalid", "true");
    expect(errorOf(screen.getByLabelText("Email"))).toBeUndefined();
    expect(errorOf(screen.getByRole("group", { name: "Topics" }))).toBe("Pick at least one topic.");
    
  6. fixing everything signs up and clears every mark
    const send = async ({ name = "", email = "", topics = [] } = {}) => {
      if (name) await user.type(screen.getByLabelText("Name"), name);
      if (email) await user.type(screen.getByLabelText("Email"), email);
      for (const topic of topics) await user.click(screen.getByLabelText(topic));
      await user.click(screen.getByRole("button", { name: "Subscribe" }));
      await flush();
    };
    const errorOf = (field) => {
      const id = field.getAttribute("aria-describedby");
      return id ? document.getElementById(id)?.textContent : undefined;
    };
    render(<NewsletterForm />);
    await send({ email: "zoe@example.com" });
    await send({ name: "Zoe", topics: ["New teas"] });
    expect(screen.getByRole("status")).toHaveTextContent("Thanks, Zoe! Check your inbox to confirm.");
    expect(screen.queryByRole("alert")).not.toBeInTheDocument();
    expect(screen.getByLabelText("Name")).not.toHaveAttribute("aria-invalid", "true");
    expect(screen.getByLabelText("Name")).not.toHaveAttribute("aria-describedby");
    expect(screen.getByRole("group", { name: "Topics" })).not.toHaveAttribute("aria-describedby");
    expect(subscribers.map((entry) => entry.email)).toEqual(["mei@example.com", "zoe@example.com"]);
    

Learn more

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