Booking works when everything goes well. If the spots run out or someone already had a booking, the action ends silently; if the number isn't valid, an error screen appears. What's missing is a return channel: the action needs to reply and the form needs to know how to render that reply.

That channel is useActionState. In this lesson you'll give an action's reply a type, show it next to the fields in an accessible way and keep what the person had typed, which React clears unless you prevent it. With that you'll build AgendaViva's biggest form: creating and editing events in the dashboard, with two buttons that do different things. Validation will still be manual and minimal; in 06-03 it moves to a schema.

  1. An action's state

useActionState takes an action and an initial value, and returns three things:

const [state, formAction, isPending] = useActionState(action, initialState)
Item What it is
state The last thing the action returned, or the initial value
formAction The function you put in action or formAction
isPending true while the action is in progress

The action's signature changes: it first receives the previous state and then FormData. If you forget, formData.get will fail, because the first argument is no longer the form.

1.1. A type for each outcome

Many examples return { message?: string, errors?: object }, all optional, and the UI fills up with checks for combinations that don't exist. A discriminated union, like the one in 04-01, describes only the possible cases:

// lib/forms.ts — neutral: used by actions and components
export type FieldErrors<Field extends string> = Partial<Record<Field, string[]>>

export type FormState<Field extends string> =
  | { status: 'initial' }
  | { status: 'success'; message: string }
  | {
      status: 'error'
      message: string
      errors: FieldErrors<Field>
      values: Record<Field, string>
    }

export const INITIAL_STATE: { status: 'initial' } = { status: 'initial' }

// Reads the fields as strings; anything missing or that's a file is left empty
export function readTextFields<Field extends string>(
  formData: FormData,
  fields: readonly Field[],
): Record<Field, string> {
  const pairs = fields.map((field) => {
    const value = formData.get(field)
    return [field, typeof value === 'string' ? value : '']
  })
  return Object.fromEntries(pairs) as Record<Field, string>
}
  • Field is the set of names. FormState<'spots'> won't let you write an error to 'spot'.
  • Each field has a list of errors, because it can break several rules. That's also the shape Zod produces.
  • values keeps what was submitted, as strings. It's used to put it back in the fields. A password field is never sent back.
  • It isn't in the action's file. INITIAL_STATE is a constant, and a 'use server' module can't export it.
  • readTextFields reads only the fields it's asked for. Object.fromEntries(formData) would be shorter, but it includes whatever anyone sent, React's internal fields whose names start with $ACTION_, and it loses repeated values.

  1. Booking, with a reply

// lib/format.ts (addition)
export function formatSpots(spots: number): string {
  return spots === 1 ? '1 spot' : `${spots} spots`
}
// actions/bookings.ts
'use server'

import { refresh } from 'next/cache'
import { createBooking, type BookingResult } from '@/lib/data/bookings'
import { readEnv } from '@/lib/env'
import { formatSpots } from '@/lib/format'
import { type FormState, readTextFields } from '@/lib/forms'
import { notifyIfAvailabilityChanges } from '@/lib/revalidation'
import { getPlaceholderUser } from '@/lib/placeholder-user'

export type BookingState = FormState<'spots'>

function explainRejection(result: Exclude<BookingResult, { status: 'booked' }>): string {
  switch (result.status) {
    case 'already-booked':
      return 'You already have a booking for this event.'
    case 'not-enough-spots':
      return result.spotsLeft === 0
        ? 'There are no spots left.'
        : `Only ${formatSpots(result.spotsLeft)} left.`
    case 'unavailable':
      return 'This event is no longer taking bookings.'
  }
}

export async function bookSpots(
  eventId: string,
  _previous: BookingState,
  formData: FormData,
): Promise<BookingState> {
  const user = await getPlaceholderUser()
  const values = readTextFields(formData, ['spots'])

  const spots = Number(values.spots)
  const { maxSpotsPerBooking: max } = readEnv()
  if (!Number.isInteger(spots) || spots < 1 || spots > max) {
    return {
      status: 'error',
      message: "The booking wasn't made.",
      errors: { spots: [`Enter a number between 1 and ${max}.`] },
      values,
    }
  }

  const result = await createBooking(user.id, eventId, spots)
  refresh()

  if (result.status !== 'booked') {
    return { status: 'error', message: explainRejection(result), errors: {}, values }
  }

  notifyIfAvailabilityChanges(result.spotsBefore, result.spotsAfter)
  return { status: 'success', message: `You've booked ${formatSpots(spots)}.` }
}

The argument fixed with bind comes first; after it, the two that useActionState supplies. The previous state isn't needed, and the underscore says so. explainRejection isn't exported, so it can't be invoked from outside, and the switch without a default makes TypeScript warn you if a new outcome appears.

Two different kinds of message: the ones in errors belong to a field that can be corrected; message talks about the whole.

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

import { useActionState } from 'react'
import { bookSpots } from '@/actions/bookings'
import { Field } from '@/components/field'
import { FormMessage } from '@/components/form-message'
import { INITIAL_STATE } from '@/lib/forms'

interface Props {
  eventId: string
  max: number
}

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

  return (
    <form action={formAction} className="mt-4">
      <FormMessage state={state} />
      <Field label="Spots" errors={error?.errors.spots}>
        {(attributes) => (
          <input
            {...attributes}
            type="number"
            name="spots"
            min={1}
            max={max}
            defaultValue={error?.values.spots ?? '1'}
            required
            className="border px-2"
          />
        )}
      </Field>
      <button disabled={isPending} className="mt-2 border px-3">
        {isPending ? 'Booking…' : 'Book'}
      </button>
    </form>
  )
}

In EventBooking, replace the <form> with <BookingForm eventId={event.id} max={max} /> and the message with You have {formatSpots(booking.spots)} booked for this event. The form is now a client one, because it uses a hook; the block that runs the queries stays on the server. And it still works without JavaScript: formAction comes from a Server Action, and React includes the returned state in the response's HTML.

To see a rejection, open the page for pottery-workshop, set its spots_left to 1 with npm run db:studio and ask for 2 without reloading: the message says how many are left and refresh adjusts the maximum. After a success, on the other hand, the block switches to showing your booking and the form disappears along with its message; the same happens if you already had one or they all ran out. In 06-04 we'll make the message survive.

  1. Showing errors

Red text isn't accessible just because it's red. An error must be associated with its field, so a screen reader reads it on reaching the field, and it must be announced when it appears.

// components/field.tsx
import { type ReactNode, useId } from 'react'

interface FieldAttributes {
  id: string
  'aria-invalid': true | undefined
  'aria-describedby': string | undefined
}

interface Props {
  label: string
  hint?: string
  errors?: string[]
  children: (attributes: FieldAttributes) => ReactNode
}

export function Field({ label, hint, errors = [], children }: Props) {
  const id = useId()
  const hintId = `${id}-hint`
  const errorsId = `${id}-errors`
  const descriptions = [hint && hintId, errors.length > 0 && errorsId].filter(Boolean)

  return (
    <div className="mb-4 flex flex-col">
      <label htmlFor={id} className="font-medium">{label}</label>
      {children({
        id,
        'aria-invalid': errors.length > 0 || undefined,
        'aria-describedby': descriptions.join(' ') || undefined,
      })}
      {hint && <p id={hintId} className="text-sm text-slate-600">{hint}</p>}
      {errors.length > 0 && (
        <ul id={errorsId} className="text-sm text-red-700">
          {errors.map((error) => <li key={error}>{error}</li>)}
        </ul>
      )}
    </div>
  )
}
// components/form-message.tsx
'use client'

import { useEffect, useRef } from 'react'
import type { FormState } from '@/lib/forms'

export function FormMessage({ state }: { state: FormState<string> }) {
  const box = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (state.status === 'error') box.current?.focus()
  }, [state])

  return (
    <div ref={box} tabIndex={-1} role="status" className="mb-2">
      {state.status === 'error' && (
        <p className="border-l-4 border-red-700 p-2">{state.message}</p>
      )}
      {state.status === 'success' && (
        <p className="border-l-4 border-green-700 p-2">{state.message}</p>
      )}
    </div>
  )
}
  • useId generates unique identifiers. With a fixed id="title", two forms in the document would clash; and with Cache Components there are hidden pages that are still in it.
  • aria-describedby links the field to its hint and its errors; aria-invalid flags it as incorrect.
  • Field receives a function that renders the control, so it works for input, textarea or select. Since it doesn't cross the boundary (whoever uses it is a client component), it can do that (03-03).
  • role="status" announces the text when it changes. The container is always on the page: a region that appears with its text already in it sometimes isn't announced.
  • Focus moves to the message when there's an error. In a long form, someone who presses the button at the bottom wouldn't see what happened at the top. Each submission produces a new object, so the effect runs again even if the message is the same.

  1. The form reset

Try removing the defaultValue from the spots field, type 3 and trigger a rejection: the field is cleared. You saw it in 06-01: when the action function finishes without throwing, React resets uncontrolled fields. And returning a validation error is finishing without throwing.

The idea behind the reset is good for a comment box and maddening for a ten-field form. The ways out:

Technique When
Return values and use them in defaultValue The norm: it works without JavaScript
Controlled fields, with useState When the UI depends on what's being typed
onSubmit with preventDefault and a transition Avoids the reset, but loses progressive enhancement

React applies the new default values before resetting, and that's why the first one works. With two caveats: on a <select>, changing defaultValue after it's mounted does nothing, so it needs a key; and a file field doesn't accept a default value, so it's always cleared (06-05).

  1. The event form

5.1. Types, dates and slug

// lib/types.ts (addition)
export const EVENT_FIELDS = [
  'title', 'summary', 'description', 'category', 'venueId', 'startsAt', 'endsAt', 'capacity',
] as const
export type EventField = (typeof EVENT_FIELDS)[number]
export type EventData = Pick<AgendaEvent, EventField>
export type EventValues = Record<EventField, string>

// What an organizer can edit on their own
export const EDITABLE_STATUSES = ['draft', 'review'] as const
export type EditableStatus = (typeof EDITABLE_STATUSES)[number]

EventData holds the values already converted; EventValues, the same fields as strings, which is what a form contains. Left out on purpose are id, slug, organizerId, spotsLeft and status: they aren't for the person filling in the form to decide.

An <input type="datetime-local"> sends 2028-05-12T20:30, with no time zone. Interpreting it with new Date would use the server's time zone, which in production is usually UTC: the concert would move by two hours. This module converts using the guide's time zone, and in 06-03 we'll look at it in detail:

// lib/dates.ts
const TIME_ZONE = 'Europe/Madrid'

const formatter = new Intl.DateTimeFormat('en', {
  timeZone: TIME_ZONE,
  year: 'numeric', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
})

// Instant → '2028-05-12T20:30' in the guide's time zone
export function formatLocalDateTime(date: Date): string {
  const p = Object.fromEntries(
    formatter.formatToParts(date).map(({ type, value }) => [type, value]),
  )
  return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}`
}

// '2028-05-12T20:30' in the guide's time zone → instant, or null if it doesn't exist
export function parseLocalDateTime(text: string): Date | null {
  if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(text)) return null

  const asUtc = Date.parse(`${text}Z`)
  if (Number.isNaN(asUtc)) return null

  const offset = (instant: number) =>
    Date.parse(`${formatLocalDateTime(new Date(instant))}Z`) - instant

  const date = new Date(asUtc - offset(asUtc - offset(asUtc)))
  return formatLocalDateTime(date) === text ? date : null
}
// lib/slug.ts
export function createSlug(title: string): string {
  const slug = title
    .normalize('NFD')
    .replace(/\p{Diacritic}/gu, '') // Removes the accents, already split off
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .slice(0, 60)
    .replace(/^-+|-+$/g, '')
  return slug || 'event'
}

5.2. Writing to the database

// lib/data/dashboard.ts (addition; imports inArray, createSlug and the types)
function isEditableBy(organizerId: string, id: string) {
  return and(
    eq(events.id, id),
    eq(events.organizerId, organizerId),
    inArray(events.status, [...EDITABLE_STATUSES]),
  )
}

export async function getEditableEvent(
  organizerId: string,
  id: string,
): Promise<AgendaEvent | null> {
  const db = await getDb()
  const [event] = await db.select().from(events).where(isEditableBy(organizerId, id)).limit(1)
  return event ?? null
}

export async function insertEvent(
  organizerId: string,
  data: EventData,
  status: EditableStatus,
): Promise<boolean> {
  const db = await getDb()
  const base = createSlug(data.title)

  for (let attempt = 1; attempt <= 5; attempt++) {
    const slug = attempt === 1 ? base : `${base}-${attempt}`
    const inserted = await db
      .insert(events)
      .values({ ...data, slug, organizerId, status, spotsLeft: data.capacity })
      .onConflictDoNothing({ target: events.slug })
      .returning({ id: events.id })
    if (inserted.length > 0) return true
  }
  throw new Error(`No free slug found for "${base}"`)
}

export async function updateEvent(
  organizerId: string,
  id: string,
  data: EventData,
  status: EditableStatus,
): Promise<boolean> {
  const db = await getDb()
  const updated = await db
    .update(events)
    .set({ ...data, status, spotsLeft: data.capacity })
    .where(isEditableBy(organizerId, id))
    .returning({ id: events.id })
  return updated.length > 0
}
  • The ownership condition is in the where. With the identifier of someone else's event, or one that's already published, no row is updated and the function returns false. Checking first and writing afterwards would leave a gap between the two.
  • The slug is created once. Editing the title doesn't change it: that way links don't break.
  • onConflictDoNothing turns the collision into "zero rows", without an exception. Asking beforehand whether it's free would have the race from 06-01.
  • spotsLeft is set to the capacity because a draft has no bookings. Editing published events, with bookings already made, is a job for 11-03.

5.3. The actions

// actions/events.ts
'use server'

import { refresh } from 'next/cache'
import { redirect } from 'next/navigation'
import { insertEvent, updateEvent } from '@/lib/data/dashboard'
import { type FormState, readTextFields } from '@/lib/forms'
import { parseEvent } from '@/lib/parse-event'
import { EVENT_FIELDS, type EventField, type EventData, type EditableStatus } from '@/lib/types'
import { getPlaceholderOrganizer } from '@/lib/placeholder-user'

export type EventFormState = FormState<EventField>

function readIntent(formData: FormData): EditableStatus {
  return formData.get('intent') === 'review' ? 'review' : 'draft'
}

async function saveEvent(
  formData: FormData,
  write: (event: EventData, status: EditableStatus) => Promise<boolean>,
): Promise<EventFormState> {
  const values = readTextFields(formData, EVENT_FIELDS)
  const parsed = parseEvent(values)
  if (!parsed.ok) {
    return { status: 'error', message: 'Check the highlighted fields.', errors: parsed.errors, values }
  }

  try {
    const saved = await write(parsed.data, readIntent(formData))
    if (!saved) {
      return { status: 'error', message: 'This event can no longer be edited.', errors: {}, values }
    }
  } catch (error) {
    console.error('Error saving an event:', error)
    return {
      status: 'error',
      message: "We couldn't save the event. Please try again.",
      errors: {},
      values,
    }
  }

  refresh()
  redirect('/dashboard/events')
}

export async function createEvent(
  _previous: EventFormState,
  formData: FormData,
): Promise<EventFormState> {
  const { id } = await getPlaceholderOrganizer()
  return saveEvent(formData, (event, status) => insertEvent(id, event, status))
}

export async function editEvent(
  eventId: string,
  _previous: EventFormState,
  formData: FormData,
): Promise<EventFormState> {
  const { id } = await getPlaceholderOrganizer()
  return saveEvent(formData, (event, status) => updateEvent(id, eventId, event, status))
}

The shared part is in saveEvent, which isn't exported: if it were, it would be another entry point. Each action only works out the identity and supplies the write.

redirect is outside the try. It works by throwing an exception that Next.js recognizes; inside, your catch would capture it and the person would see "We couldn't save" with the event already saved. Since it never returns, TypeScript accepts that there's no final return. Without JavaScript it responds with a 303, and reloading the destination page doesn't resubmit the form.

Here the unexpected failure is caught, unlike in reads (02-04). The criterion is the one from 04-01, whether the UI can do something sensible: it can, keeping what was typed. An exception would show the error boundary and ten minutes of work would be lost. The detail is logged and a neutral sentence is returned.

refresh before redirecting discards the pages stored for back and forward navigation, including the previous list. No public data changes, so there are no tags to invalidate (05-04).

// lib/parse-event.ts — temporary: a schema replaces it in 06-03
type ParseResult =
  | { ok: true; data: EventData }
  | { ok: false; errors: FieldErrors<EventField> }

export function parseEvent(values: EventValues): ParseResult {
  const errors: FieldErrors<EventField> = {}

  const title = values.title.trim()
  if (title.length < 5) errors.title = ['Write at least 5 characters.']

  const category = CATEGORIES.find((option) => option === values.category)
  if (!category) errors.category = ['Choose a category.']

  const startsAt = parseLocalDateTime(values.startsAt)
  if (!startsAt) errors.startsAt = ['Enter a date and time.']

  // … endsAt (after startsAt) and capacity (positive integer), the same way

  if (!category || !startsAt || !endsAt || Object.keys(errors).length > 0) {
    return { ok: false, errors }
  }
  const { summary, description, venueId } = values
  return {
    ok: true,
    data: { title, summary, description, category, venueId, startsAt, endsAt, capacity },
  }
}

Finish it, even though it won't last long. It doesn't limit lengths and it accepts a nonexistent venue, which will make the foreign key fail. You can already sense why a schema is worth it.

5.4. The component

// app/(dashboard)/dashboard/events/_components/event-form.tsx
'use client'

import { useActionState } from 'react'
import { useRouter } from 'next/navigation'
import type { EventFormState } from '@/actions/events'
import { Field } from '@/components/field'
import { FormMessage } from '@/components/form-message'
import { CATEGORY_LABELS } from '@/lib/format'
import { INITIAL_STATE } from '@/lib/forms'
import { CATEGORIES, type VenueSummary, type EventValues } from '@/lib/types'

interface Props {
  action: (
    previous: EventFormState,
    formData: FormData,
  ) => Promise<EventFormState>
  initial: EventValues
  venues: VenueSummary[]
}

export function EventForm(props: Props) {
  const { bfcacheId } = useRouter()
  return <EventFields key={bfcacheId} {...props} />
}

function EventFields({ action, initial, venues }: Props) {
  const [state, formAction, isPending] = useActionState(action, INITIAL_STATE)
  const error = state.status === 'error' ? state : null
  const values = error?.values ?? initial

  return (
    <form action={formAction} className="max-w-xl">
      <FormMessage state={state} />

      <Field label="Title" errors={error?.errors.title}>
        {(attributes) => (
          <input {...attributes} name="title" defaultValue={values.title} required />
        )}
      </Field>

      <Field label="Category" errors={error?.errors.category}>
        {(attributes) => (
          <select
            {...attributes}
            key={values.category}
            name="category"
            defaultValue={values.category}
            required
          >
            <option value="">Choose one</option>
            {CATEGORIES.map((category) => (
              <option key={category} value={category}>
                {CATEGORY_LABELS[category]}
              </option>
            ))}
          </select>
        )}
      </Field>

      {/* summary and description (textarea), venueId (select with key), capacity (number),
          startsAt and endsAt (datetime-local): the same */}

      <div className="flex gap-2">
        <button name="intent" value="draft" disabled={isPending}>
          Save draft
        </button>
        <button name="intent" value="review" disabled={isPending}>
          Submit for review
        </button>
      </div>
    </form>
  )
}

Write the six missing fields following the same pattern; venueId loops over venues. The pages only prepare the data. This is the edit page:

// app/(dashboard)/dashboard/events/[id]/edit/page.tsx
type Props = PageProps<'/dashboard/events/[id]/edit'>

export default async function EditEventPage({ params }: Props) {
  const { id } = await params
  const organizer = await getPlaceholderOrganizer()
  const [event, venues] = await Promise.all([
    getEditableEvent(organizer.id, id),
    listVenueSummaries(),
  ])
  if (!event) notFound()

  return (
    <>
      <h1 className="mb-6 text-2xl font-bold">Edit event</h1>
      <EventForm
        action={editEvent.bind(null, event.id)}
        initial={valuesFromEvent(event)}
        venues={venues}
      />
    </>
  )
}
// lib/event-values.ts
import { formatLocalDateTime } from '@/lib/dates'
import type { AgendaEvent, EventValues } from '@/lib/types'

export const EMPTY_VALUES: EventValues = {
  title: '', summary: '', description: '', category: '',
  venueId: '', startsAt: '', endsAt: '', capacity: '',
}

export function valuesFromEvent(event: AgendaEvent): EventValues {
  const { title, summary, description, category, venueId, capacity } = event
  return {
    title, summary, description, category, venueId,
    startsAt: formatLocalDateTime(event.startsAt),
    endsAt: formatLocalDateTime(event.endsAt),
    capacity: String(capacity),
  }
}

NewEventPage, in dashboard/events/new/page.tsx, is the same without an event: action={createEvent} and initial={EMPTY_VALUES}.

  • One component, two actions. The edit page fixes the identifier with bind and passes the function as a prop. It's called action following the convention from 03-03.
  • The page's wait is covered by the loading.tsx in dashboard/events/ (02-04).
  • Dates are converted on the server. Only strings reach the component, and there are no mismatches when hydrating.
  • The two buttons share a name. Only the clicked button's value is sent, with JavaScript and without it. The first one is the one triggered by Enter: it should be the less committal one. Don't combine name with a formAction that's a function, because React needs that attribute for itself.
  • values.category as the key of the <select>, for the reason given in section 4.

In DashboardEventsPage, add a "New event" link to /dashboard/events/new and, on rows in draft or review, another one to /dashboard/events/${event.id}/edit. The seed data has no events from usr-02 in those statuses: create one.

5.5. Why that key with bfcacheId

Pages aren't unmounted when you leave them (02-01). If someone submits the form with an error, fixes it, saves and later comes back to "New event", they'd find the fields and the message from the previous time.

useRouter().bfcacheId is an identifier that changes when the route is created by a fresh navigation, for example a Link, and stays the same when going back, going forward and refreshing. As a key, it gives exactly what you'd expect: a link opens a clean form and the back button brings back the draft. The documentation presents it as a last resort and prefers resetting state in the corresponding event handler; here the event is a redirect that happens on the server, and there's no handler to do it in.

Common Mistakes and Tips

  • Forgetting the previous state in the signature. formData receives the state and get doesn't exist.
  • Putting redirect inside the try.
  • Throwing validation errors. They're returned; in production a thrown message doesn't arrive.
  • Not returning the values. React resets the form after an error too.
  • Expecting a <select> to follow its defaultValue without a key.
  • Visible but unassociated errors: no aria-describedby and no announcement.
  • Wrapping the action in a client function for no reason: it loses progressive enhancement.
  • Including fields in the form that aren't for the person filling it in to decide, such as the status or the organizer.
  • Checking ownership only when showing the page. The action can be invoked without it.

Exercises

Exercise 1: discarding a draft

On the edit page, add a "Discard" button that deletes the event if it's one of your own drafts and goes back to the list. It must ask for confirmation. What mechanism do you use, and what happens without JavaScript?

Solution

// lib/data/dashboard.ts
export async function deleteDraft(organizerId: string, id: string): Promise<void> {
  const db = await getDb()
  await db
    .delete(events)
    .where(and(isEditableBy(organizerId, id), eq(events.status, 'draft')))
}

// actions/events.ts
export async function discardEvent(id: string): Promise<void> {
  const organizer = await getPlaceholderOrganizer()
  await deleteDraft(organizer.id, id)
  refresh()
  redirect('/dashboard/events')
}

On the page, a separate <form> (forms can't be nested) with action={discardEvent.bind(null, event.id)}. The confirmation goes in a Client Component with onSubmit={(e) => { if (!confirm('Discard the draft?')) e.preventDefault() }}: canceling the submission prevents the action from running. Without JavaScript it would be deleted without asking. If that's unacceptable, the confirmation has to be an intermediate page. Deleting something that no longer exists isn't an error: the result is the desired one. The course leaves this as practice.

Exercise 2: diagnosing

This form has four symptoms: when it fails it's cleared, "Save" always shows "Unexpected error" even though it saves, the screen reader says nothing, and with JavaScript disabled it does nothing. Find the causes.

// The action, trimmed
try {
  await saveVenue(formData)
  redirect('/venues')
} catch {
  return { error: 'Unexpected error' }
}

// The component
const [state, formAction] = useActionState(save, { error: '' })
return (
  <form action={async (formData) => formAction(formData)}>
    <input name="name" />
    {state.error && <p className="text-red-700">{state.error}</p>}
    <button>Save</button>
  </form>
)

Solution

  • It's cleared because the action doesn't return the values and the field has no defaultValue.
  • "Unexpected error" because redirect throws inside the try.
  • The reader stays silent because the paragraph isn't in a region with role="status" or associated with the field; besides, the field has no label.
  • It doesn't work without JavaScript because action receives a client function. You have to pass formAction directly.

Conclusion

useActionState gives an action a return channel: the action receives the previous state and FormData, and returns a value that the form renders. That value is a discriminated union with a message, errors per field and the submitted strings, which are returned because React resets the fields after an error too. Errors are associated, announced and given focus. What's expected is returned, what's unexpected is logged, and redirect goes outside the try. Two buttons with the same name and different values are enough for two intents.

The weak spot is parseEvent: a lot of lines to check very little, and the same manual work in booking, in parseForecast and in readEnv. In Server-Side Data Validation you'll replace them with Zod schemas.

© Copyright 2026. All rights reserved