Skip to content

Form Actions

The Course
•
20 min study

Saving to a server means waiting, and the wait needs handling: disable the button so it isn't pressed twice, show that something is happening, show what went wrong. React 19's actions handle much of that for you.

A pretend server

api.js waits 600 ms, then saves the card, or refuses any title containing fail.

Saving with an action React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. It takes a moment to answer, and refuses any card whose // title contains "fail", so you can see what happens when saving goes wrong. export async function saveCard(title, minutes) { await new Promise((resolve) => setTimeout(resolve, 600)); if (title.toLowerCase().includes("fail")) throw new Error("The server refused the card."); return { id: Date.now(), title, minutes, column: "todo" }; } import { useActionState } from "react"; import { saveCard } from "./api.js"; async function addCard(previous, formData) { const title = String(formData.get("title")).trim(); const minutes = Number(formData.get("minutes")); if (title === "") return { ...previous, error: "Enter a title." }; try { const card = await saveCard(title, minutes); return { cards: [...previous.cards, card], error: null }; } catch (error) { return { ...previous, error: error.message }; } } export default function App() { const [state, formAction, isPending] = useActionState(addCard, { cards: [], error: null }); return ( <main> <h1>Add study cards</h1> <form action={formAction} className="toolbar"> <input name="title" aria-label="Title" placeholder="Title" /> <input name="minutes" aria-label="Minutes" type="number" defaultValue="15" style={{ width: "5rem" }} /> <button disabled={isPending}>{isPending ? "Saving…" : "Add"}</button> </form> {state.error && <p className="error">{state.error}</p>} <ul className="cards"> {state.cards.map((card) => ( <li key={card.id} className="card">{card.title} <span className="muted">{card.minutes} min</span></li> ))} </ul> </main> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Try a blank title, then Hooks, then This will fail.

A function as the form's action

JSX
<form action={formAction}>
  <input name="title" />
  ...
</form>

When action is a function, submitting the form calls it with a FormData holding every named field. You don't call preventDefault, and the inputs don't need state: formData.get("title") reads the value when it's needed.

useActionState

JavaScript
const [state, formAction, isPending] = useActionState(addCard, { cards: [], error: null });
  • addCard(previous, formData) is the action. It gets the last state and the form data, and returns the next state. It can be async:

    JavaScript
    async function addCard(previous, formData) {
      const title = String(formData.get("title")).trim();
      const minutes = Number(formData.get("minutes"));
      if (title === "") return { ...previous, error: "Enter a title." };
      try {
        const card = await saveCard(title, minutes);
        return { cards: [...previous.cards, card], error: null };
      } catch (error) {
        return { ...previous, error: error.message };
      }
    }
  • state is whatever the action last returned, starting with the initial value.

  • isPending is true while the action runs. The button uses it to disable itself and say Saving….

It works like a reducer whose "actions" are form submissions, and it can wait for a server.

After the action

When an action finishes, React resets the form: uncontrolled fields go back to their default values. After Hooks is saved, the title box is empty and ready for the next card.

Predict

Type This will fail and press Add. What's in the title box afterwards?

Check your prediction

It's empty, although nothing was saved. The form resets because this action catches the server error and returns an error state normally. React sees a completed action; it doesn't interpret the returned error field. An uncaught exception is a different path and belongs with error handling, not this form's validation state. The error message stays, because it's in state. Fixing that is this lesson's exercise.

Exercise

Keep the title after a failure

Make the title box keep the refused title, so the user can fix it instead of retyping it.

Your working space React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. It takes a moment to answer, and refuses any card whose // title contains "fail", so you can see what happens when saving goes wrong. export async function saveCard(title, minutes) { await new Promise((resolve) => setTimeout(resolve, 600)); if (title.toLowerCase().includes("fail")) throw new Error("The server refused the card."); return { id: Date.now(), title, minutes, column: "todo" }; } import { useActionState } from "react"; import { saveCard } from "./api.js"; async function addCard(previous, formData) { const title = String(formData.get("title")).trim(); const minutes = Number(formData.get("minutes")); if (title === "") return { ...previous, error: "Enter a title." }; try { const card = await saveCard(title, minutes); return { cards: [...previous.cards, card], error: null }; } catch (error) { return { ...previous, error: error.message }; } } export default function App() { const [state, formAction, isPending] = useActionState(addCard, { cards: [], error: null }); return ( <main> <h1>Add study cards</h1> <form action={formAction} className="toolbar"> <input name="title" aria-label="Title" placeholder="Title" /> <input name="minutes" aria-label="Minutes" type="number" defaultValue="15" style={{ width: "5rem" }} /> <button disabled={isPending}>{isPending ? "Saving…" : "Add"}</button> </form> {state.error && <p className="error">{state.error}</p>} <ul className="cards"> {state.cards.map((card) => ( <li key={card.id} className="card">{card.title} <span className="muted">{card.minutes} min</span></li> ))} </ul> </main> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

After an action, React resets the form's fields to their default values. So the title survives only if the next default value is the refused title. The action already knows that title, and whatever it returns becomes the new state, which the form can read.

Hint 2: a first step

First make the failure branch of the action return the title as well as the error, and show it under the form for now, such as <p>{state.title}</p>. Submit a title that's refused: the paragraph shows it, but the box is empty. Now make the box start from that value. Which prop sets an uncontrolled input's starting text? And what should the title be after a successful save?

Show one solution
JavaScript
try {
  const card = await saveCard(title, minutes);
  return { cards: [...previous.cards, card], error: null, title: "" };
} catch (error) {
  return { ...previous, error: error.message, title };
}
JSX
<input name="title" aria-label="Title" placeholder="Title" defaultValue={state.title ?? ""} />

Was this article helpful?

Your response is saved on this device.