In the client component NoteForm, useActionState wraps the action:
state is the action's latest result, starting with the second argument;
formAction goes on the form, in place of addNote;
pending is true while it runs.
The form shows state.error in an element with role="alert", which screen
readers announce, and it's linked to the input with aria-describedby.
defaultValue={state.text} puts back what the reader typed, so a mistake doesn't
cost them their work:
Add required to the input. Now an empty box doesn't even send: the browser
stops it and shows its own message. That's quicker for the reader. But try
submitting only spaces: the browser lets those through, and the server's check
catches them. Anyone can send anything to your server, so the server always
checks, whatever the browser does.
Exercise
Not too long
Refuse notes longer than 60 characters with Keep notes under 60
characters., keeping the text in the box.
Your working spaceNext.js · 7 filesimport Link from "next/link";
import "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<nav>
<Link href="/">Notes</Link>
<Link href="/new">New note</Link>
</nav>
</header>
{children}
</body>
</html>
);
}
import { getNotes } from "@/lib/notes.js";
// Read the notes fresh on every request.
export const dynamic = "force-dynamic";
export default async function HomePage() {
const notes = await getNotes();
return (
<main>
<h1>Notes</h1>
<ul>
{notes.map((note) => <li key={note.id}>{note.text}</li>)}
</ul>
</main>
);
}
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { createNote } from "@/lib/notes.js";
// Used with useActionState: it gets the previous result first, and returns
// the next one. Returning ends the action; redirect() leaves the page.
export async function addNote(previous, formData) {
const text = String(formData.get("text") ?? "").trim();
if (text === "") {
return { error: "Write something first.", text };
}
await createNote(text);
revalidatePath("/");
redirect("/");
}
body {
font: 16px/1.5 system-ui, sans-serif;
margin: 0;
color: #1c2430;
}
header,
main,
footer {
max-width: 36rem;
margin: 0 auto;
padding: 0.75rem 1rem;
}
header {
border-bottom: 1px solid #d6dde6;
}
nav {
display: flex;
gap: 1rem;
}
a {
color: #06617f;
}
h1 {
margin: 0.5rem 0;
}
.muted {
color: #5b6876;
}
.card {
border: 1px solid #d6dde6;
border-radius: 8px;
padding: 0.75rem 1rem;
margin-bottom: 0.75rem;
}
"use client";
import { useActionState } from "react";
import { addNote } from "../actions.js";
export default function NoteForm() {
const [state, formAction, pending] = useActionState(addNote, { error: null, text: "" });
return (
<form action={formAction}>
<p>
<input name="text" aria-label="Note" defaultValue={state.text} aria-describedby="note-error" />
</p>
<p id="note-error" role="alert">{state.error}</p>
<button disabled={pending}>{pending ? "Saving…" : "Save"}</button>
</form>
);
}
import NoteForm from "./NoteForm.jsx";
export default function NewNotePage() {
return (
<main>
<h1>New note</h1>
<NoteForm />
</main>
);
}
// A pretend database, kept in the server's memory. A real app would use a
// database; memory is emptied whenever the server restarts (here, every Run).
const notes = [{ id: 1, text: "Read about server actions", done: false }];
let nextId = 2;
const wait = () => new Promise((resolve) => setTimeout(resolve, 400));
export async function getNotes() {
return notes;
}
export async function createNote(text) {
await wait();
notes.push({ id: nextId++, text, done: false });
}
export async function deleteNote(id) {
await wait();
const index = notes.findIndex((note) => note.id === id);
if (index !== -1) notes.splice(index, 1);
}
export async function toggleNote(id) {
await wait();
const note = notes.find((note) => note.id === id);
if (note) note.done = !note.done;
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
The server owns the validation rule. Return a recoverable error with the submitted value instead of discarding the draft.
Hint 2: a first step
Add a second check in addNote, after the blank check, that returns the same
shape as the blank check does. Test it with a note of 61 characters: the error
should show and the box should still hold your text.
Show one solution
JavaScript
if (text.length > 60) { return { error: "Keep notes under 60 characters.", text };}await createNote(text);
The check runs in the action, on the server, so it holds even for a request
that doesn't come from this form. text has already been trimmed, so spaces
around a note don't count. Returning text with the error lets the form put
the draft back. A maxLength on the input is a kind extra, not a replacement:
anyone can remove it in devtools.
Completion is saved in this browser only. It does not measure mastery.