Skip to content

Checkpoint: A Reading List

The Course
•
20 min study

Close the earlier lessons and build this from the brief. lib/books.js has getBooks(), createBook(title) and deleteBook(id).

The brief

A Reading List on one page:

  • The books, each with a × button named Remove plus its title for screen readers. With no books: Nothing to read yet.
  • A Book title field and an Add book button. While adding, the button says Adding… and is disabled.
  • The server checks the title: blank gives Enter a title.; over 40 characters gives Keep the title under 40 characters., keeping what was typed. Errors are announced with role="alert".
  • After a successful add, the field is empty and the error is gone.

Acceptance checks: press Add book with nothing typed; add a long title; add Clean Code; remove both books.

Your workspace Next.js · 4 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Reading List</header> {children} </body> </html> ); } import { getBooks } from "@/lib/books.js"; // Build the reading list here. See the brief. export const dynamic = "force-dynamic"; export default async function HomePage() { const books = await getBooks(); return ( <main> <h1>To read</h1> <p className="muted">{books.length} book</p> </main> ); } 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 of books, in the server's memory. const books = [{ id: 1, title: "Learning React" }]; let nextId = 2; const wait = () => new Promise((resolve) => setTimeout(resolve, 400)); export async function getBooks() { return books; } export async function createBook(title) { await wait(); books.push({ id: nextId++, title }); } export async function deleteBook(id) { await wait(); const index = books.findIndex((book) => book.id === id); if (index !== -1) books.splice(index, 1); }
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 files

app/actions.js with addBook(previous, formData) and removeBook(id), and a client app/BookForm.jsx using useActionState.

Hint 2: emptying the field

Return { error: null, title: "" } on success. To make the input take the new defaultValue, give it key={state.title}: a new key makes React create a fresh input.

Show one solution
One solution Next.js · 6 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Reading List</header> {children} </body> </html> ); } import { getBooks } from "@/lib/books.js"; import { removeBook } from "./actions.js"; import BookForm from "./BookForm.jsx"; export const dynamic = "force-dynamic"; export default async function HomePage() { const books = await getBooks(); return ( <main> <h1>To read</h1> {books.length === 0 ? ( <p className="muted">Nothing to read yet.</p> ) : ( <ul> {books.map((book) => ( <li key={book.id}> {book.title}{" "} <form action={removeBook.bind(null, book.id)} style={{ display: "inline" }}> <button aria-label={`Remove ${book.title}`}>×</button> </form> </li> ))} </ul> )} <BookForm /> </main> ); } "use server"; import { revalidatePath } from "next/cache"; import { createBook, deleteBook } from "@/lib/books.js"; export async function addBook(previous, formData) { const title = String(formData.get("title") ?? "").trim(); if (title === "") return { error: "Enter a title.", title }; if (title.length > 40) return { error: "Keep the title under 40 characters.", title }; await createBook(title); revalidatePath("/"); return { error: null, title: "" }; } export async function removeBook(id) { await deleteBook(id); revalidatePath("/"); } "use client"; import { useActionState } from "react"; import { addBook } from "./actions.js"; export default function BookForm() { const [state, formAction, pending] = useActionState(addBook, { error: null, title: "" }); return ( <form action={formAction}> <input key={state.title} name="title" aria-label="Book title" defaultValue={state.title} />{" "} <button disabled={pending}>{pending ? "Adding…" : "Add book"}</button> <p role="alert">{state.error}</p> </form> ); } 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 of books, in the server's memory. const books = [{ id: 1, title: "Learning React" }]; let nextId = 2; const wait = () => new Promise((resolve) => setTimeout(resolve, 400)); export async function getBooks() { return books; } export async function createBook(title) { await wait(); books.push({ id: nextId++, title }); } export async function deleteBook(id) { await wait(); const index = books.findIndex((book) => book.id === id); if (index !== -1) books.splice(index, 1); }
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.

Check yourself

  1. Where does a server action run, and how does a form call it?
  2. What does revalidatePath do, and what happens without it?
  3. Why does the server validate input even when the browser already does?

Was this article helpful?

Your response is saved on this device.