AgendaViva's actions are correct and, seen from the other side, silent. The district button doesn't react when you press it; the live spots take a while to go down after booking; when you save an event, the list appears without saying that everything went fine. With a 300 ms artificial delay it's already annoying; on a mobile connection, people press again.

This lesson is about what happens between the click and the response, and right after it. You'll see how to show that something is in progress, when it's worth showing the result before you have it and how to undo it if it fails, what stops a double submission from doing damage, how to notify the data the browser holds, and how to leave a message that survives a redirect. By the end, AgendaViva will have the /my-bookings page.

  1. Three ways to know something is in progress

Where it's used What it provides
Third value of useActionState In the component that declares the action Whether that action is in progress
useFormStatus (from react-dom) In a component inside the <form> pending, and the data being sent
useTransition When invoking without a form [isPending, startTransition]

All three tell the same story: the action is a transition and stays pending until it finishes and the new screen arrives. There's no need to coordinate a "saving" with a "refreshing".

1.1. A reusable button

useFormStatus fits a button, because it needs no props and doesn't need to know which action is involved:

// components/submit-button.tsx
'use client'

import type { ComponentProps } from 'react'
import { useFormStatus } from 'react-dom'

interface Props extends Omit<ComponentProps<'button'>, 'type' | 'disabled'> {
  pendingText: string
}

export function SubmitButton({ children, pendingText, name, value, ...rest }: Props) {
  const { pending, data } = useFormStatus()
  const isClicked = pending && (!name || data?.get(name) === value)

  return (
    <button {...rest} type="submit" name={name} value={value} disabled={pending}>
      {isClicked ? pendingText : children}
    </button>
  )
}
// DistrictForm: still a Server Component
<SubmitButton pendingText="Saving…" className="border px-3">Save</SubmitButton>

// EventForm
<SubmitButton name="intent" value="draft" pendingText="Saving…">
  Save draft
</SubmitButton>
<SubmitButton name="intent" value="review" pendingText="Submitting…">
  Submit for review
</SubmitButton>
  • It must be in a separate component, a child of the form. Called in the same component that writes the <form>, pending is always false.
  • data is the FormData being sent, including the value of the clicked button. That way, of two buttons, only one changes its text, and both are disabled.
  • Disabling on submit doesn't lose the button's value. React collects the data first.
  • DistrictForm stays on the server and keeps working without JavaScript. Only the button is an island.

In EventForm, the third value of useActionState goes away. An accessibility detail: when it's disabled, the button loses focus. After an error, FormMessage receives it; if the form stayed on screen after a success, you'd have to give it back.

1.2. How much feedback

Expected wait What to do
Less than a few tenths of a second Nothing, or a subtle change: flickering text is worse
A second Button text, and disable it
Longer Also say what's happening; with files, the progress (06-05)
Very predictable result Optimistic update

  1. The message that disappeared

In 06-02 there was a loose end: after booking, the server returned a different block, the form was unmounted and its message went with it. The solution is for the component holding the state not to move: a single one, always present, that renders both cases.

// app/(public)/events/_components/booking-panel.tsx (replaces booking-form.tsx)
'use client'

import { useActionState, useEffect } from 'react'
import Link from 'next/link'
import { useSWRConfig } from 'swr'
import { bookSpots } from '@/actions/bookings'
import { SubmitButton } from '@/components/submit-button'
import { Field } from '@/components/field'
import { FormMessage } from '@/components/form-message'
import { formatSpots } from '@/lib/format'
import { INITIAL_STATE } from '@/lib/forms'
import { availabilityPath } from '@/lib/api-routes'

interface Props {
  eventId: string
  slug: string
  bookedSpots: number | null
  max: number
}

export function BookingPanel({ eventId, slug, bookedSpots, max }: Props) {
  const [state, formAction] = useActionState(bookSpots.bind(null, eventId), INITIAL_STATE)
  const error = state.status === 'error' ? state : null

  const { mutate } = useSWRConfig()
  useEffect(() => {
    if (state.status !== 'initial') void mutate(availabilityPath(slug))
  }, [state, mutate, slug])

  return (
    <section aria-label="Booking" className="mt-4">
      <FormMessage state={state} />
      {bookedSpots !== null && (
        <p>
          You have {formatSpots(bookedSpots)} booked for this event.{' '}
          <Link href="/my-bookings" className="underline">Manage my bookings</Link>
        </p>
      )}
      {bookedSpots === null && max > 0 && (
        <form action={formAction}>
          {/* the same Field with the spots input from 06-02, which uses error */}
          <SubmitButton pendingText="Booking…" className="border px-3">Book</SubmitButton>
        </form>
      )}
    </section>
  )
}
// event-booking.tsx (from the Promise.all on)
if (!booking && (!availability || event.endsAt <= new Date())) return null

const { maxSpotsPerBooking } = readEnv()
return (
  <BookingPanel
    eventId={event.id}
    slug={event.slug}
    bookedSpots={booking?.spots ?? null}
    max={Math.min(maxSpotsPerBooking, availability?.spotsLeft ?? 0)}
  />
)

Now refresh brings new props to the same component: React keeps state and the "You've booked 2 spots" message stays, even though the form is gone. Since the button that had focus disappears, change the effect's condition in FormMessage to state.status !== 'initial': focus will move to the message after a success too. Delete booking-form.tsx.

It's a general rule. React state belongs to a position in the tree; if the server's response changes that position, the state is lost.

  1. Notifying SWR

The effect in the previous component ties up the other loose end. refresh renews what the server renders, but LiveAvailability shows what SWR holds, and once mounted it ignores the new fallbackData. There are two copies and both need to be notified.

// lib/api-routes.ts
export function availabilityPath(slug: string): string {
  return `/api/events/${slug}/availability`
}

mutate(key), with no data, marks that entry as stale and requests it again if any mounted component uses it. The key must be identical, so LiveAvailability switches to using availabilityPath(slug) too. It's the same reasoning that centralized the tags in 05-03.

It's notified both after a success and after a rejection: if the spots ran out, the number the person was seeing was old. And it's in an effect, not in a function wrapping formAction, so that action still receives the action directly and the form works before hydration.

mutate also accepts a provisional value (optimisticData, with rollbackOnError), useful when the mutation goes through SWR. With Server Actions, the natural tool is the next one.

  1. Optimistic updates

An optimistic update renders the result before the server confirms it. React provides it with useOptimistic:

const [visible, update] = useOptimistic(actualValue, reducer)

While no action is in progress, visible is actualValue. When you call update inside an action, visible becomes the reducer's result, and when the action finishes it goes back to actualValue. That's the key: there's nothing to undo. If it went well, the actual value will have changed and you won't notice; if it went wrong, the actual value is the same as always and the UI rolls back on its own.

sequenceDiagram
    participant P as Screen
    participant S as Server
    P->>P: update(id) and the row disappears
    P->>S: cancelMyBooking(id)
    alt success
      S-->>P: new list, without the row
      Note over P: back to the actual value, which no longer has it
    else failure
      S-->>P: error
      Note over P: back to the actual value, which has it, and a notice is shown
    end

Two obligations follow from this. The action must renew the actual value (with refresh, a tag or a setState): otherwise, the row would reappear after being deleted successfully. And the failure must be reported: a row that comes back without explanation looks like a bug.

4.1. When it's worth it

Operation Optimistic? Why
Canceling your own booking Yes It almost never fails, and visually undoing it misleads nobody
Marking a favorite Yes Frequent, reversible and with no consequences
Reordering a list Yes Waiting on every move would make it unusable
Booking No It can be rejected for a real reason; saying "booked" and taking it back is worse than waiting
Submitting an event for review No There's validation, and when it finishes the page changes
Paying, deleting with no way back No The "done" has to be true

For booking, the honest thing is a pending state. You could use useOptimistic to show "Booking 2 spots…" instead of the form, as long as the text is in the present tense:

// Example only
const [inProgress, mark] = useOptimistic<string | null>(null)

<form
  action={(formData) => {
    mark(String(formData.get('spots')))
    formAction(formData)
  }}
>
  {inProgress && <p>Booking {inProgress}…</p>}

We don't adopt it: action would receive a client function and progressive enhancement would be lost for a text the button already provides.

  1. My bookings

5.1. Data and action

// lib/data/bookings.ts (addition; imports asc)
export type CancellationResult =
  | { status: 'canceled'; spotsBefore: number; spotsAfter: number }
  | { status: 'not-found' }

export async function listUserBookings(userId: string) {
  const db = await getDb()
  return db
    .select({
      id: bookings.id,
      spots: bookings.spots,
      slug: events.slug,
      title: events.title,
      startsAt: events.startsAt,
    })
    .from(bookings)
    .innerJoin(events, eq(bookings.eventId, events.id))
    .where(eq(bookings.userId, userId))
    .orderBy(asc(events.startsAt), asc(bookings.id))
}

export async function cancelBooking(
  userId: string,
  bookingId: string,
): Promise<CancellationResult> {
  const db = await getDb()

  return db.transaction(async (tx): Promise<CancellationResult> => {
    const [canceled] = await tx
      .delete(bookings)
      .where(and(eq(bookings.id, bookingId), eq(bookings.userId, userId)))
      .returning({ eventId: bookings.eventId, spots: bookings.spots })
    if (!canceled) return { status: 'not-found' }

    const [event] = await tx
      .update(events)
      .set({ spotsLeft: sql`${events.spotsLeft} + ${canceled.spots}` })
      .where(eq(events.id, canceled.eventId))
      .returning({ spotsLeft: events.spotsLeft })
    if (!event) throw new Error('The booking pointed to a nonexistent event')

    return {
      status: 'canceled',
      spotsBefore: event.spotsLeft - canceled.spots,
      spotsAfter: event.spotsLeft,
    }
  })
}
// actions/bookings.ts (addition)
export async function cancelMyBooking(bookingId: string): Promise<void> {
  const user = await getPlaceholderUser()
  if (!identifier.safeParse(bookingId).success) throw new Error('Invalid booking')

  const result = await cancelBooking(user.id, bookingId)
  if (result.status === 'canceled') {
    notifyIfAvailabilityChanges(result.spotsBefore, result.spotsAfter)
  }
  refresh()
}
  • The delete is the check. With the user in the where, someone else's booking isn't deleted; returning says whether there was anything to delete and how many spots to give back. Two simultaneous cancellations don't give them back twice: the second doesn't find the row.
  • not-found isn't an error. Whoever cancels wants there to be no booking, and there isn't one. An operation that can be repeated without changing the result is called idempotent.
  • The addition is done in SQL, on the current value, not on one read earlier.
  • The impossible does throw: a three-kilobyte identifier doesn't come from our UI.

5.2. The page

// app/(public)/my-bookings/page.tsx
export default function MyBookingsPage() {
  return (
    <>
      <h1 className="mb-6 text-3xl font-bold">My bookings</h1>
      <ErrorBoundary title="We can't show your bookings">
        <Suspense fallback={<ListSkeleton items={3} />}>
          <UserBookings />
        </Suspense>
      </ErrorBoundary>
    </>
  )
}

async function UserBookings() {
  const user = await getPlaceholderUser()
  const bookings = await listUserBookings(user.id)

  return (
    <BookingList
      bookings={bookings.map(({ startsAt, ...booking }) => ({
        ...booking,
        date: formatDateTime(startsAt),
      }))}
    />
  )
}
// app/(public)/my-bookings/_components/booking-list.tsx
'use client'

import { useOptimistic, useState, useTransition } from 'react'
import Link from 'next/link'
import { useSWRConfig } from 'swr'
import { cancelMyBooking } from '@/actions/bookings'
import { formatSpots } from '@/lib/format'
import { availabilityPath } from '@/lib/api-routes'

interface ListedBooking {
  id: string
  spots: number
  slug: string
  title: string
  date: string
}

export function BookingList({ bookings }: { bookings: ListedBooking[] }) {
  const [visible, remove] = useOptimistic(bookings, (current, id: string) =>
    current.filter((booking) => booking.id !== id),
  )
  const [notice, setNotice] = useState('')
  const [, startTransition] = useTransition()
  const { mutate } = useSWRConfig()

  function handleCancel({ id, slug, title }: ListedBooking) {
    setNotice('')
    startTransition(async () => {
      remove(id)
      let message = `You've canceled your booking for "${title}".`
      try {
        await cancelMyBooking(id)
        void mutate(availabilityPath(slug))
      } catch {
        message = `We couldn't cancel your booking for "${title}". Please try again.`
      }
      startTransition(() => setNotice(message))
    })
  }

  return (
    <>
      <p role="status" className="mb-4 min-h-6">{notice}</p>
      {visible.length === 0 && <p>You don't have any bookings.</p>}
      <ul className="grid gap-4">
        {visible.map((booking) => (
          <li key={booking.id} className="flex justify-between border p-4">
            <div>
              <Link href={`/events/${booking.slug}`} className="font-semibold">
                {booking.title}
              </Link>
              <p>{booking.date}. {formatSpots(booking.spots)}</p>
            </div>
            <button
              type="button"
              onClick={() => handleCancel(booking)}
              aria-label={`Cancel the booking for ${booking.title}`}
            >
              Cancel
            </button>
          </li>
        ))}
      </ul>
    </>
  )
}
  • remove can only be called inside an action: here, the startTransition function. Outside one, React warns and the change lasts an instant.
  • The reducer is pure and is applied to the actual value of the moment. If two are canceled in a row, the actions run in series (06-01), and both rows stay hidden until everything finishes.
  • The second startTransition is needed because whatever follows an await is no longer part of the transition; it's a current limitation of React. Without it, the message could appear before the list.
  • The try covers the network and the server. Without catching, a failure would go to the error boundary and replace the whole page, too much for a cancellation. In production the error message wouldn't arrive, so we write our own.
  • Dates arrive as text, formatted on the server: less is sent and there are no mismatches when hydrating.

Add the "My bookings" link to Header. To see the rollback, open the page, stop PostgreSQL with docker compose stop and cancel: the row disappears instantly and comes back with the notice.

  1. What about favorites?

FavoriteButton already responds instantly and needs none of this: it writes to localStorage, which is synchronous and local (03-02). useOptimistic only makes sense when the actual value is far away. If favorites were stored in the account, the button would look like this:

// Example only: AgendaViva keeps favorites in the browser
export function AccountFavoriteButton({ eventId, isFavorite }: Props) {
  const [visible, setVisible] = useOptimistic(isFavorite)

  return (
    <form
      action={async () => {
        const next = !visible
        setVisible(next)
        await setFavorite(eventId, next)
      }}
    >
      <button aria-pressed={visible}>{visible ? '★' : '☆'}</button>
    </form>
  )
}

Look at the action: setFavorite(id, value), not toggleFavorite(id). With "toggle", if a submission is repeated or arrives late, the result is inverted. Stating the value you want is idempotent: it doesn't matter how many times it arrives.

  1. Double submission

Disabling the button prevents most of them, but not all: before hydration there's no button to disable, someone may have two tabs open, and an unstable network repeats requests. The defense is in layers:

Layer What it prevents
Button disabled while submitting The double click
Redirecting after writing Resubmission on reload (the 303 turns the POST into a GET)
Idempotent operation Repeating changing anything
Unique constraint Two simultaneous requests leaving two rows
Idempotency key The same, when there's no natural constraint

This is where our operations stand:

  • Booking: unique per person and event, plus the lock. The second one gets already-booked.
  • Canceling: idempotent.
  • Saving the district and editing an event: they write a final value; repeating changes nothing.
  • Creating an event: the only exposed one. Two submissions give two drafts, the second with a slug ending in -2. It's harmless, because a draft can be discarded; exercise 2 closes it off completely.

  1. Messages after redirecting

When you save an event you're redirected to the list, and the form's state stays on the page you're leaving. You need a message that's read once at the destination. These are called flash messages. The options:

Where Advantage Drawback
Parameter, ?notice=saved Trivial Reappears on reload, when going back and in a copied link
Short-lived cookie It's consumed; the URL stays clean A bit more code
Global client state Allows animations Lost without JavaScript
// lib/flash.ts (neutral)
export const FLASH_COOKIE = 'agendaviva-flash'

export const FLASH_MESSAGES = {
  'draft-saved': 'Draft saved.',
  'event-submitted': 'Event submitted for review.',
} as const

export type FlashKey = keyof typeof FLASH_MESSAGES

export function isFlashKey(value: string): value is FlashKey {
  return Object.hasOwn(FLASH_MESSAGES, value)
}
// lib/flash-server.ts
import 'server-only'
import { cookies } from 'next/headers'
import { FLASH_MESSAGES, type FlashKey, FLASH_COOKIE, isFlashKey } from '@/lib/flash'

// Server Actions only
export async function setFlash(key: FlashKey): Promise<void> {
  const cookieStore = await cookies()
  cookieStore.set(FLASH_COOKIE, `${key}.${Date.now()}`, {
    path: '/',
    sameSite: 'lax',
    secure: process.env.NODE_ENV === 'production',
    maxAge: 30,
  })
}

export async function readFlash(): Promise<{ text: string; stamp: string } | null> {
  const cookieStore = await cookies()
  const stamp = cookieStore.get(FLASH_COOKIE)?.value ?? ''
  const [key = ''] = stamp.split('.')
  return isFlashKey(key) ? { text: FLASH_MESSAGES[key], stamp } : null
}
// components/flash-notice.tsx
import { readFlash } from '@/lib/flash-server'
import { FlashMessage } from './flash-message'

export async function FlashNotice() {
  const flash = await readFlash()
  return flash ? <FlashMessage key={flash.stamp} text={flash.text} /> : null
}

// components/flash-message.tsx
'use client'

import { useEffect, useState } from 'react'
import { FLASH_COOKIE } from '@/lib/flash'

export function FlashMessage({ text }: { text: string }) {
  const [closed, setClosed] = useState(false)

  useEffect(() => {
    document.cookie = `${FLASH_COOKIE}=; path=/; max-age=0`
  }, [])

  if (closed) return null
  return (
    <div role="status" className="mb-4 flex justify-between border-l-4 border-green-700 p-2">
      {text}
      <button type="button" onClick={() => setClosed(true)}>Close</button>
    </div>
  )
}
// actions/events.ts, before refresh()
await setFlash(status === 'review' ? 'event-submitted' : 'draft-saved')

// DashboardEventsPage, after the <h1>
<Suspense fallback={null}>
  <FlashNotice />
</Suspense>
  • The cookie stores a key, not the text. If it stored the message, anyone who managed to write it could put whatever they liked on your page. And this way it can be translated (09-05).
  • It isn't httpOnly because the browser deletes it: a Server Component can't write cookies. If the effect never gets to run, it expires in half a minute.
  • The timestamp tells two identical messages in a row apart. As a key, it creates a new FlashMessage even if the previous one had been closed.
  • It doesn't close on its own. A message that disappears after three seconds doesn't give enough time to someone who reads slowly or zooms in on the screen.
  • It's on the destination page and not in the layout, which isn't rendered again when navigating between its pages (02-01).

Common Mistakes and Tips

  • Calling useFormStatus in the component that writes the <form>.
  • Storing "loading" in a useState. It gets out of sync; the transition already knows.
  • Being optimistic about something that can be rejected.
  • Forgetting to renew the actual value: the optimistic change is undone after a success.
  • Rolling back without explaining why.
  • Actions that toggle instead of setting a value.
  • Relying only on the disabled button.
  • SWR keys written by hand in two places.
  • Moving the component that holds the state and losing the message.
  • Free text in a cookie or in the URL that ends up on screen.

Exercises

Exercise 1: confirming without getting in the way

You're asked to make canceling a booking reversible for a few seconds with an "Undo" button, instead of asking beforehand. Describe two designs, one that delays the action and another that runs it and reverts it, and their problems.

Solution

  • Delaying: the row is hidden with local state and the action is triggered after five seconds, unless it's undone. It's simple, but if the tab is closed or the person navigates away, the cancellation never happens; with Cache Components, on top of that, the page is hidden and its effects are cleaned up. You'd have to trigger it on hide, with no guarantees.
  • Running and reverting: it's canceled right away, and "Undo" tries to book again. The result is always consistent, but in those seconds someone else may have taken the spots, and undoing would fail.

For scarce spots, neither is perfect. A third option is for the server to mark the booking as "recently canceled" and release the spots later. In AgendaViva, where you can book again, canceling and showing a notice is enough.

Exercise 2: idempotency key

Make submitting the "New event" form twice create a single draft. Explain why you can't use crypto.randomUUID() when rendering the field, and what happens without JavaScript.

Solution

// lib/db/schema.ts, in events (with its migration)
submissionKey: text('submission_key').unique(),

// EventFields: the key is generated once, already in the browser
const keyField = useRef<HTMLInputElement>(null)
useEffect(() => {
  if (keyField.current && !keyField.current.defaultValue) {
    keyField.current.defaultValue = crypto.randomUUID()
  }
}, [])

<input ref={keyField} type="hidden" name="submissionKey" />

The key is included when inserting, and onConflictDoNothing is extended: if nothing is inserted and a row with that key from the same organizer already exists, it returns true, because the work is done.

Generating it while rendering would mean a random value in the prerender, which Cache Components rejects (05-01), and if it were accepted, every visitor would share the same one. defaultValue is used so that React's reset doesn't clear it. Without JavaScript the field arrives empty, which must be stored as null; unique allows several nulls and you fall back to the previous behavior. The course doesn't keep it.

Exercise 3: finding the bug

This component marks notices as read. Sometimes a notice is marked and, when it finishes, shows up as unread again, even though it's read in the database. Other times, the console warns about an optimistic change outside a transition. Fix it.

// The action only runs an UPDATE
const [readIds, addReadIds] = useOptimistic(readNoticeIds)

async function handleClick(id: string) {
  await markAsRead(id)
  addReadIds([...readIds, id])
}

Solution

  • addReadIds is called outside a transition and, on top of that, after waiting: it's neither optimistic nor allowed.
  • The action doesn't renew anything, so readNoticeIds stays the same and, when it finishes, the UI rolls back. refresh() is missing from the action.
  • Computing the value from readIds can lose changes if two are clicked in a row; a reducer is better.
const [readIds, addReadIds] = useOptimistic(readNoticeIds, (current, id: string) => [
  ...current,
  id,
])
const [, startTransition] = useTransition()

function handleClick(id: string) {
  startTransition(async () => {
    addReadIds(id)
    await markAsRead(id)
  })
}

Conclusion

Between the click and the response, useFormStatus, useActionState and useTransition say what's in progress. useOptimistic shows an almost-certain result in advance and goes back on its own to the actual value, which the action must renew; it's reserved for what's frequent and reversible. Protection against double submission isn't the button, but idempotent operations and constraints in the database. What the browser holds is notified with mutate, and a message that has to survive a redirect travels as a key in a short-lived cookie.

So far the forms have sent text. Events still have no poster, because a file raises other questions: how much it can weigh, what it really is, where it's stored and who deletes it. Those are the questions in File Uploads, the last lesson of the module.

© Copyright 2026. All rights reserved