Skip to the code

A submit button that knows its form is sending

Every form at Leaf and Kettle, from reviews to the tasting journal, ends with the same button, and it should show when its form is being sent. Write it: app/components/submit-button.tsx, a Client Component whose default export is SubmitButton({ children, pendingText }).

It renders a <button type="submit"> showing children. While the form it sits in is being sent, that is while the form's action runs, the button is disabled and shows pendingText instead. pendingText is optional: without it, the button keeps showing children while it's disabled.

Read the form's state with useFormStatus() from react-dom. Its pending is true while the <form> around the button is being sent, so the form doesn't pass the button anything, and a button in another form on the same page isn't affected.

The journal page, app/journal/page.tsx, is a Server Component. It renders the button inside a form whose action is the saveNote Server Action, which takes 400 ms.

<form action={saveNote}>
  <textarea name="note" />
  <SubmitButton pendingText="Saving…">Save note</SubmitButton>
</form>
 
Click → [Saving…] (disabled), then 400 ms later [Save note]

The app's other files

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

/** Every note saved so far: a stand-in for the shop's database. */
export const notes: string[] = [];

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

"use server";
 
import { notes } from "@/lib/notes";
 
export async function saveNote(formData: FormData) {
  await new Promise((resolve) => setTimeout(resolve, 400));
  notes.push(String(formData.get("note") ?? ""));
}

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

import { saveNote } from "@/app/actions";
import SubmitButton from "@/app/components/submit-button";
 
export default function JournalPage() {
  return (
    <main>
      <h1>Tasting journal</h1>
      <form action={saveNote}>
        <label>
          Note <textarea name="note" />
        </label>
        <SubmitButton pendingText="Saving…">Save note</SubmitButton>
      </form>
    </main>
  );
}

What the tests check

  1. is a submit button with its label
    render(
      <form>
        <SubmitButton pendingText="Saving…">Save note</SubmitButton>
      </form>,
    );
    const button = screen.getByRole("button", { name: "Save note" });
    expect(button).toHaveAttribute("type", "submit");
    expect(button).toBeEnabled();
    
  2. is a Client Component the journal 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: "Tasting journal" })).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Save note" })).toBeEnabled();
    
  3. is disabled and shows the pending text while the Server Action runs
    const clock = useFakeTimers();
    await renderServer(<Page />);
    await user.type(screen.getByLabelText("Note"), "Steeped the oolong twice.");
    await user.click(screen.getByRole("button", { name: "Save note" }));
    await flush();
    expect(screen.getByRole("button", { name: "Saving…" })).toBeDisabled();
    await clock.advance(400);
    expect(screen.getByRole("button", { name: "Save note" })).toBeEnabled();
    expect(notes).toEqual(["Steeped the oolong twice."]);
    
  4. a second click while it's sending doesn't send the form again
    const clock = useFakeTimers();
    await renderServer(<Page />);
    await user.type(screen.getByLabelText("Note"), "Mint, five minutes.");
    await user.click(screen.getByRole("button", { name: "Save note" }));
    await flush();
    await user.click(screen.getByRole("button", { name: "Saving…" }));
    await clock.advance(1000);
    expect(notes).toEqual(["Mint, five minutes."]);
    
  5. only follows its own form
    const slow = (ms) => async () => {
      await new Promise((resolve) => setTimeout(resolve, ms));
    };
    const clock = useFakeTimers();
    render(
      <>
        <form action={slow(500)}>
          <SubmitButton pendingText="Saving…">Save</SubmitButton>
        </form>
        <form action={slow(500)}>
          <SubmitButton pendingText="Sending…">Send</SubmitButton>
        </form>
      </>,
    );
    await user.click(screen.getByRole("button", { name: "Save" }));
    await flush();
    expect(screen.getByRole("button", { name: "Saving…" })).toBeDisabled();
    expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();
    await clock.advance(500);
    expect(screen.getByRole("button", { name: "Save" })).toBeEnabled();
    
  6. keeps its label while sending when there's no pending text
    const slow = (ms) => async () => {
      await new Promise((resolve) => setTimeout(resolve, ms));
    };
    const clock = useFakeTimers();
    render(
      <form action={slow(300)}>
        <SubmitButton>Subscribe</SubmitButton>
      </form>,
    );
    await user.click(screen.getByRole("button", { name: "Subscribe" }));
    await flush();
    expect(screen.getByRole("button", { name: "Subscribe" })).toBeDisabled();
    await clock.advance(300);
    expect(screen.getByRole("button", { name: "Subscribe" })).toBeEnabled();
    

Learn more

app/components/submit-button.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).