Skip to content

Checkpoint: Add Cards with Actions

The Course
•
20 min study

Close the earlier lessons and build this from the brief. The starter's form saves cards, but shows nothing while saving, saves blank titles, and loses failures: try This will fail and see what happens.

The brief

Rebuild the form with a form action:

  • useActionState holds { error }. A blank title returns Enter a title. without calling the server. A refused card returns "This will fail" wasn't saved: The server refused the card.
  • While saving, the button is disabled and says Saving….
  • useOptimistic shows each new card at once, faded, with Saving…, until the server answers. A refused card disappears.
  • Under the form, 3 cards saved counts only cards the server confirmed.

Acceptance checks:

  • Add with a blank title shows the error and sends nothing.
  • Adding Quick one shows it immediately as saving, then as saved, and the count goes from 2 to 3.
  • This will fail appears, disappears, and leaves the error. The count doesn't change.
Your workspace React · 5 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 { useState } from "react"; import { saveCard } from "./api.js"; import { starterCards } from "./data.js"; // Adding works, but nothing shows while saving, failures are lost, and a // blank title is saved. Rebuild the form with actions. See the brief. export default function App() { const [cards, setCards] = useState(starterCards.slice(0, 2)); const [title, setTitle] = useState(""); async function handleSubmit(event) { event.preventDefault(); const card = await saveCard(title, 15); setCards([...cards, card]); setTitle(""); } return ( <main> <h1>Study Board</h1> <form onSubmit={handleSubmit} className="toolbar"> <input aria-label="Title" placeholder="Title" value={title} onChange={(e) => setTitle(e.target.value)} /> <button>Add</button> </form> <ul className="cards"> {cards.map((card) => ( <li key={card.id} className="card">{card.title}</li> ))} </ul> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; 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: one action, two hooks

The function you pass to useActionState is the action, so call addOptimisticCard inside it, before the await.

Hint 2: the count

Count cards, the real state, not optimisticCards.

Show one solution
One solution React · 5 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, useOptimistic, startTransition, useState } from "react"; import { saveCard } from "./api.js"; import { starterCards } from "./data.js"; export default function App() { const [cards, setCards] = useState(starterCards.slice(0, 2)); const [optimisticCards, addOptimisticCard] = useOptimistic( cards, (current, title) => [...current, { id: `saving-${title}`, title, saving: true }] ); async function addCard(previous, formData) { const title = String(formData.get("title")).trim(); if (title === "") return { error: "Enter a title." }; addOptimisticCard(title); try { const card = await saveCard(title, 15); startTransition(() => setCards((current) => [...current, card])); return { error: null }; } catch (error) { return { error: `"${title}" wasn't saved: ${error.message}` }; } } const [state, formAction, isPending] = useActionState(addCard, { error: null }); return ( <main> <h1>Study Board</h1> <form action={formAction} className="toolbar"> <input name="title" aria-label="Title" placeholder="Title" /> <button disabled={isPending}>{isPending ? "Saving…" : "Add"}</button> </form> {state.error && <p className="error">{state.error}</p>} <p className="muted">{cards.length} cards saved</p> <ul className="cards"> {optimisticCards.map((card) => ( <li key={card.id} className="card" style={card.saving ? { opacity: 0.6 } : undefined}> {card.title} {card.saving && <span className="muted">Saving…</span>} </li> ))} </ul> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; 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.

Check yourself

  1. Why doesn't memo help when a parent passes a new arrow function each render?
  2. What does useDeferredValue let React do with a slow render?
  3. Why don't optimistic updates need rollback code when saving fails?

Was this article helpful?

Your response is saved on this device.