Skip to content

Actions for Each Item

The Course
•
20 min study

A delete button needs to say which note. Its action needs the note's id.

Delete a note Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Study Notes</header> {children} </body> </html> ); } import { getNotes } from "@/lib/notes.js"; import { addNote, removeNote } from "./actions.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}{" "} <form action={removeNote.bind(null, note.id)} style={{ display: "inline" }}> <button aria-label={`Delete ${note.text}`}>×</button> </form> </li> ))} </ul> <form action={addNote}> <input name="text" aria-label="New note" /> <button>Add</button> </form> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { createNote, deleteNote } from "@/lib/notes.js"; export async function addNote(formData) { await createNote(formData.get("text")); revalidatePath("/"); } // Called with the note's id bound in front: removeNote.bind(null, note.id). export async function removeNote(id) { console.log("Removing note", id); await deleteNote(id); revalidatePath("/"); } 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; } // 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.
Add and remove files here; write their code in the editor.

Add two notes, then delete one with ×. Look at the console.

bind

JSX
<form action={removeNote.bind(null, note.id)}>
  <button aria-label={`Delete ${note.text}`}>×</button>
</form>
JavaScript
export async function removeNote(id) {
  await deleteNote(id);
  revalidatePath("/");
}

removeNote.bind(null, note.id) makes a new function with the id filled in as its first argument. Each note's form gets its own, so pressing a button calls removeNote(2) or removeNote(3). The null is a detail of bind; always pass null here.

Each button is a tiny form. That's normal in Next.js: a form is how the browser calls a server action, and it works even before the page's JavaScript has loaded.

The × alone means nothing to a screen reader, so each button has an aria-label naming its note.

Why not onClick?

The page is a server component, so it can't use onClick, as Day 2 showed. You could write a client component that calls removeNote(note.id) from a click handler; that works too. A form keeps the page on the server and needs no client code at all.

Exercise

Mark done

Add a ✓ button before each × that marks a note done, drawing a line through it. Pressing it again (now ↺) marks it not done. lib/notes.js already has toggleNote(id).

Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Study Notes</header> {children} </body> </html> ); } import { getNotes } from "@/lib/notes.js"; import { addNote, removeNote } from "./actions.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}{" "} <form action={removeNote.bind(null, note.id)} style={{ display: "inline" }}> <button aria-label={`Delete ${note.text}`}>×</button> </form> </li> ))} </ul> <form action={addNote}> <input name="text" aria-label="New note" /> <button>Add</button> </form> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { createNote, deleteNote } from "@/lib/notes.js"; export async function addNote(formData) { await createNote(formData.get("text")); revalidatePath("/"); } // Called with the note's id bound in front: removeNote.bind(null, note.id). export async function removeNote(id) { console.log("Removing note", id); await deleteNote(id); revalidatePath("/"); } 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; } // 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.
Add and remove files here; write their code in the editor.
Hint 1: the idea

Marking a note done changes server data, just like deleting one. So it's the same shape: a Server Action changes the data and refreshes the page, and each note's form tells the action which note it is.

Hint 2: a first step

Write a toggleDone(id) action next to removeNote, and give each note a second form bound to its id, like the × form, with a ✓ button. Press it twice and check note.done flips. Then draw the line through the text, switch the symbol, and give the button a name that says what it will do.

Show one solution

In actions.js:

JavaScript
import { createNote, deleteNote, toggleNote } from "@/lib/notes.js";

export async function toggleDone(id) {
  await toggleNote(id);
  revalidatePath("/");
}

In page.jsx, import toggleDone, and in each item:

JSX
<span style={{ textDecoration: note.done ? "line-through" : "none" }}>{note.text}</span>{" "}
<form action={toggleDone.bind(null, note.id)} style={{ display: "inline" }}>
  <button aria-label={`Mark ${note.text} ${note.done ? "not done" : "done"}`}>{note.done ? "↺" : "✓"}</button>
</form>{" "}

bind(null, note.id) fills in the action's first argument, so each form changes its own note without a hidden input. revalidatePath("/") makes the server render the list again with the new done. The aria-label names what the button will do next, because ✓ and ↺ alone say nothing to a screen reader.

Was this article helpful?

Your response is saved on this device.