Forms from submit to database

Intermediate · 26 min

Trace a Taskboard form submit from browser to database row and back: pending state, server field errors, double submits and what to clear on success.

Before thisServer state vs UI stateValidating on the client and the serverError handling across the stack

Programming Fields · 26 min

Forms from submit to database

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Programming FieldsReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A form submit crosses every layer, so it has to handle client validation, a pending state, server validation errors, a database conflict and a success that updates the cache.
  • Server field errors should come back in the same map shape as client ones, so a single loop can attach each message to the matching input.
  • While the request is in flight, disable the submit button or ignore repeat clicks, otherwise a double click creates two rows.
  • On success, invalidate the affected queries and reset the form, and on failure, keep what the user typed.
  • An error that belongs to no field, such as a network failure or a 500, goes in a form-level message rather than being attached to an arbitrary input.

One click, five places

The user fills in a new task title and presses Add. Follow that single action:

  1. The browser checks the value with the shared schema.
  2. A request goes out, and the button should show that something is happening.
  3. The API validates again and checks permission.
  4. The database inserts a row, or refuses.
  5. The response returns, and the screen has to reflect success or the reason for failure.

A form that handles only step 1 and the success case in step 5 will look fine in a demo and break on the first real user. This lesson fills in the rest. The browser-only version is in forms and controlled inputs and controlled vs uncontrolled components; here the interesting part is the crossing.

What the server sends back

You built the error shape in the earlier lessons, so the form can lean on it. Posting an invalid task to Taskboard’s API returned:

{"error":{"code":"validation","message":"Fix the highlighted fields","fields":{"title":["Give the task a title"],"status":["Invalid option: expected one of \"todo\"|\"doing\"|\"done\""]}}} 

with status 422. A duplicate sign-up returned 409 with fields: {"email": ["Already registered"]}. And a request the server could not handle (I sent malformed JSON) returned 400 bad_json, which has no fields at all.

That gives the form three cases to handle:

Response Attach to
fields present The matching inputs
Error with no fields (400, 401, 404, 500) A message at the top of the form
No response at all (network) The same top message, with a retry

Mapping errors to inputs

Because the server’s fields map uses the same keys as the inputs, one loop does the attaching. With React Hook Form (from its documentation; I ran the API side, not this component):

const { register, handleSubmit, setError, reset, formState } = useForm<CreateTask>({
  resolver: zodResolver(createTask),
});
const qc = useQueryClient();
const add = useMutation({
  mutationFn: (v: CreateTask) => addTask(projectId, v),   // throws ApiFailure on non-2xx
  onSuccess: () => { qc.invalidateQueries({ queryKey: ["board", projectId] }); reset(); },
  onError: (e) => {
    if (e instanceof ApiFailure && e.fields) {
      for (const [name, msgs] of Object.entries(e.fields))
        setError(name as keyof CreateTask, { message: msgs[0] });
    } else {
      setError("root", { message: e instanceof ApiFailure ? e.message : "Could not reach the server" });
    }
  },
});

Look at what each branch does with the user’s text. On failure the form is not reset, so the user keeps what they typed and fixes only the wrong field. On success it is reset and the board’s cache entry is invalidated, so the new task appears from fresh server state. That follows server state vs UI state: the draft is UI state and goes away; the list is server state and gets refetched.

The root error is the form-level message, for failures that belong to no field. Do not stick a “something went wrong” on the title input; it misleads the user about what to fix.

The double submit

Press Add twice quickly. Without a guard you create two tasks. Two defences, and you want both:

  • Client: disable the button while the mutation is pending (add.isPending). It is cheap and removes most accidents.
  • Server: make the create safe to retry. A client can send a one-time Idempotency-Key header, and the server stores the result under that key so a repeat returns the same answer. Idempotency keys in practice shows the implementation. For a task title it is overkill; for a payment it is mandatory.

A disabled button does not help when a flaky network makes the browser retry silently, or when the user submits in two tabs. That is why the server side is the real fix.

Writes need the right status

The status codes the form depends on:

  • 201 Created for a new row, with the new row in the body, so the client can add it without a refetch if it wants.
  • 422 for field validation, 409 for a conflict with existing data.
  • 401 if the session expired mid-form. Do not lose the draft: keep the form open, send the user through sign-in, and resubmit.

The easiest way to find the form’s missing states is to run the real thing and break it: submit empty, submit a duplicate, kill the API, expire the session cookie, double-click. In this lesson’s API, the empty title, the duplicate email and the malformed body each gave different responses, which is exactly why the form needs three branches.

Server actions and framework forms

Frameworks with server-side form handling, such as Next.js server actions, move the submit function to the server and give you hooks for pending state and returned errors. The shape of the problem does not change: validate, return field errors, keep the draft, show a pending state. Server actions and mutations and validation and error handling in actions cover those versions. If you stay with a separate API, as Taskboard does, the code above is the pattern.

Accessibility of errors

An error that appears visually but is not announced is invisible to a screen reader user. Link each message to its input with aria-describedby, set aria-invalid on the input, and move focus to the first invalid field or to a summary after a failed submit. Forms and form validation and accessibility in React apps go through it.

What the video covers

Programming Fields’ “How to Handle API Validation Errors in React | Show Server Errors in Forms | React 19 - Ep 12” is about 26 minutes, published January 2026. It is episode 12 of a series that pairs React 19 with a Laravel REST API, so the backend half is PHP, not our stack. Its description says it covers why client-side validation alone is not enough, how the Laravel API sends validation errors (a 422 response), and showing those errors in the React form. The server details differ from Taskboard’s but the React-side idea is the same. I could not read a transcript and I judged English from the title and description only. It is a partial fit, and it is the best focused match I found for server errors in a React form. ByteGrad’s useActionState video is linked as the framework-form version; it is sponsor-supported.

Where this fits

A form is a request that waits for the server. For small changes like ticking a task off, waiting is the wrong feel. Next: optimistic updates and consistency.

Check yourself

  1. 01What shape does the server use for field errors, and why?

    A fields map from input name to a list of messages, the same shape the client's Zod validation produces, so the form has one code path for showing them.

  2. 02What should the form do with the user's input when the server rejects it?

    Keep it, so the user can fix the one wrong field instead of retyping everything.

  3. 03How do you stop a double click from creating two tasks?

    Disable the submit button while the mutation is pending, and ideally make the server tolerate a retry, for example with an idempotency key.

  4. 04Where does a 500 error message appear on the form?

    In a form-level message, since it belongs to the whole submission and not to any single field.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark