Sub topic 4
Writing the action function
This chapter assumes you know React function components, useState, the FormData API, and async functions. It also assumes you have seen the useActionState signature from the previous chapter. Here we focus on the function you pass as the first argument.
What the action function is
The action function is the code that runs when a form is submitted. useActionState calls it for you. It does not call it with the arguments an event handler gets. Instead it passes two things:
prevState: the state from the last run. On the first submission, this is the initial state you gave the hook.formData: aFormDataobject built from the form's named fields.
Whatever the function returns becomes the next state. React re-renders the component with that value.
async function subscribe(prevState, formData) {
const email = String(formData.get("email") ?? "");
if (!email.includes("@")) {
return { ok: false, error: "Enter a valid email address.", email };
}
await fetch("/api/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
return { ok: true, error: null, email: "" };
}Reading the form data
formData.get(name) reads the field whose name attribute matches. It returns a string, a File, or null if the field is missing. Convert the value before you use it. String(formData.get("email") ?? "") gives you a string even when the field is absent.
Fields only appear in FormData if they have a name. An input without one is silently left out, which is a common first bug.
The previous state argument
Many actions ignore prevState. The subscribe action above builds a fresh result each time. Use prevState when the next state depends on the last one. This example appends to an array:
import { useActionState } from "react";
async function addItem(prevItems, formData) {
const name = String(formData.get("name") ?? "").trim();
if (!name) return prevItems;
return [...prevItems, name];
}
export function ShoppingList() {
const [items, formAction] = useActionState(addItem, []);
return (
<form action={formAction}>
<input name="name" type="text" />
<button type="submit">Add</button>
<ul>
{items.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
</form>
);
}Two points apply here. The function returns a new array and never calls push on prevItems, because state must not be mutated. When the input is empty, it returns prevItems unchanged, which means "nothing happened."
Rules for a good action function
- Always return a value. If a code path returns
undefined, your state becomesundefinedand the component may crash when it readsstate.error. - Return the same shape every time. If one branch returns
{ ok, error, email }, every branch should. Rendering code then needs no special cases. - Do not mutate
prevState. Build a new object or array. - Keep it free of rendering concerns. The action decides what happened. The component decides how to show it.
- Expect asynchrony. The function can
awaitnetwork calls. While it runs,isPendingistrue.
What happens during a submission
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Writing `(formData)` as the only parameter | `formData` is actually the previous state, so `.get` is not a function | Use `(prevState, formData)` |
| Missing `name` on an input | The field is absent from `FormData` | Add `name="..."` |
| Returning nothing on some branch | State becomes `undefined` | Return a full state object |
| Mutating `prevState` | Updates may not re-render | Return a new value |
Exercise
A teammate writes async function save(formData) { const title = formData.get("title"); ... } and passes it to useActionState. It throws "formData.get is not a function". What is wrong, and how do you fix it?
Show answer
useActionState passes the previous state as the first argument and the FormData as the second. The function's formData parameter is really the previous state. Change the signature to async function save(prevState, formData), and make sure every branch returns the next state.