Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Working with APIs

Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field

A book form that runs the API's own rules (a Zod schema generated from the spec) in the browser, sends nothing when pages is 0, and shows the server's 400 'title is required' under the Title field with setError.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Working with APIs

What you will learn

  • Run a Zod schema generated from the API contract with safeParse
  • Plug that schema into useForm with zodResolver and submit with handleSubmit
  • Use register and valueAsNumber so typing does not re-render and pages arrives as a number
  • Put a server 400 message under the right field with setError

Before you start

  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • Mutations and Optimistic Updates in TanStack Query

A form to add a book has a title, an author and pages. The API has rules for each: title is required, author is required, pages must be more than zero. The browser should run the same rules first, so bad input stops right there without a request. And when the server still says no, its message should show up under the same field.

The browser checks for speed. The server checks for safety. This article wires both into one form with React Hook Form and Zod, and every message and count comes from a real run in Chrome.

One set of rules, checked twice Add book form CreateBookBody (browser) pages 0: fails, 0 requests message under Pages title " ": passes 1 POST to the API 400, setError under Title
Either way, the user sees the message in the same place: under the field.

The rules come from the contract

We don't type the rules again. The API's spec describes a new book as BookRequest: title and author are strings with minLength 1 and are required; pages is an integer with exclusiveMinimum 0. npm run api lets Orval turn that into a Zod schema (how that works is in the Orval article):

export const createBookBodyPagesExclusiveMin = 0;

export const CreateBookBody = zod.object({
  "title": zod.string().min(1),
  "author": zod.string().min(1),
  "pages": zod.int().gt(createBookBodyPagesExclusiveMin).optional()
})

minLength 1 became .min(1), exclusiveMinimum 0 became .gt(0), and pages is .optional() because this spec did not list it as required (generated from the FastAPI Book API, pages comes out required). The file is generated, so you regenerate it when the API changes, never edit it.

The schema on its own

Before any form, run the schema with no browser at all:

// The generated rules on their own: no form, no
// browser. What does CreateBookBody say?
import { CreateBookBody } from '../src/api/books.zod'

const book = {
  title: 'The Witches',
  author: 'Roald Dahl',
  pages: 208,
}

function check(label: string, body: unknown) {
  const res = CreateBookBody.safeParse(body)
  if (res.success) return console.log(label, '-> ok')
  for (const issue of res.error.issues) {
    const where = issue.path.join('.') + ':'
    console.log(label, '->', where, issue.message)
  }
}

check('pages 208  ', book)
check('pages 0    ', { ...book, pages: 0 })
check('title "   "', { ...book, title: '   ' })
// a text field gives a string: no valueAsNumber
check('pages "208"', { ...book, pages: '208' })
pages 208   -> ok
pages 0     -> pages: Too small: expected number to be >0
title "   " -> ok
pages "208" -> pages: Invalid input: expected number, received string

safeParse checks every field and gives back either success or a list of issues, each with a path (which field) and a message. Two results to remember: three spaces pass, because three spaces are three characters, and the text "208" fails, because it is a string, not a number.

useForm runs the schema

import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { CreateBookBody } from './api/books.zod'
import { useAddBook, type Values } from './useAddBook'

export default function AddBookForm() {
  // the rules come from the API's own contract
  const form = useForm<Values>({
    resolver: zodResolver(CreateBookBody),
  })
  const { register, handleSubmit, formState } = form
  const { errors } = formState
  const add = useAddBook(form)

  // called only when every rule passes
  function onValid(data: Values) {
    add.mutate({ data })
  }

  return (
    <form onSubmit={handleSubmit(onValid)}>
      <input
        placeholder="Title"
        {...register('title')}
      />
      <p className="error">{errors.title?.message}</p>
      <input
        placeholder="Author"
        {...register('author')}
      />
      <p className="error">{errors.author?.message}</p>
      <input
        type="number"
        placeholder="Pages"
        // an input gives text; this makes it a number
        {...register('pages', { valueAsNumber: true })}
      />
      <p className="error">{errors.pages?.message}</p>

      <button disabled={add.isPending}>
        Add book
      </button>
    </form>
  )
}

// BREAK IT: drop { valueAsNumber: true } and pages
// arrives as the text "208". Zod then says:
// pages: Invalid input: expected number, received string
  • zodResolver(CreateBookBody) wraps the schema so React Hook Form can run it.
  • register connects a field, handleSubmit checks the values and only then calls your function, and formState.errors holds the messages (empty until a rule fails).
  • onValid runs only when every rule passes, and calls add.mutate to send the book.

register: the field keeps its value

register('title') returns a name, an onChange, an onBlur and a ref, and the spread puts them on the input. The ref hands the real input element to the form, so the text stays in the field and in the form's own store, not in React state. In the project's measurement, typing The Witches (11 keys) re-rendered AddBookForm 0 times. The same field kept in useState re-rendered 11 times, one per key. On a big form that adds up.

valueAsNumber: text becomes a number

Even type="number" gives its value as text. Without { valueAsNumber: true }, pages arrives as "208" and the schema says expected number, received string, the same failure as in rules.ts. With it, React Hook Form turns the text into 208. An empty pages field becomes NaN, and the message under Pages reads Invalid input: expected number, received NaN.

Stopped in the browser

Title The Witches, author Roald Dahl, pages 0, and the user clicks Add book. handleSubmit reads the values, runs the schema, and the pages rule fails. onValid is never called, so there is no mutate and no fetch:

pages 0, Add pressed      -> messages: {"title":"","author":"","pages":"Too small: expected number to be >0"} | POST requests sent: 0
The library form filled with The Witches, Roald Dahl and 0 pages. Under the pages field a red message says Too small: expected number to be >0. The page still shows 12 books.
Pages 0 never leaves the browser: the message is under Pages and the count is still 12 books.

A rule only the server has

Now the title is three spaces. The schema passes, so onValid runs and one request goes out: a POST to /api/books with "title": " ". The server has a stricter rule, a title of only spaces is blank, and answers:

400 Bad Request
Content-Type: application/problem+json
{"detail":"The book has invalid fields","instance":"/api/books","status":400,"title":"Invalid book","errors":{"title":"title is required"}}

The response is not ok, so our customFetch throws an ApiError carrying the status and the parsed body:

export async function customFetch<T>(
  url: string,
  options: RequestInit,
): Promise<T> {
  const res = await fetch(url, options)
  const text = await res.text()
  const body = text ? JSON.parse(text) : undefined
  // fetch only throws on network errors, so 4xx and
  // 5xx are turned into an error here, once
  if (!res.ok) throw new ApiError(res.status, body)
  return body as T
}

setError: same field, same place

import { useQueryClient } from '@tanstack/react-query'
import type { UseFormReturn } from 'react-hook-form'
import type { z } from 'zod'
import {
  getGetBooksQueryKey,
  useCreateBook,
} from './api/books'
import type { CreateBookBody } from './api/books.zod'
import { ApiError } from './api/fetcher'

export type Values = z.infer<typeof CreateBookBody>

// a 400 Problem Detail has errors: field -> message
type Problem = { errors?: Record<string, string> }

export function useAddBook(
  form: UseFormReturn<Values>,
) {
  const queryClient = useQueryClient()
  return useCreateBook({
    mutation: {
      onSuccess: () => {
        form.reset() // empty form again
        return queryClient.invalidateQueries({
          queryKey: getGetBooksQueryKey(),
        })
      },
      // the server still checks: put its message
      // under the same field the browser uses
      onError: (error) => {
        if (!(error instanceof ApiError)) return
        const { errors } = error.body as Problem
        const fields = Object.entries(errors ?? {})
        for (const [field, message] of fields) {
          const name = field as keyof Values
          form.setError(name, { message })
        }
      },
    },
  })
}

onError checks that the error is our ApiError, takes the errors map out of the body (field name to message), turns it into pairs with Object.entries, and calls form.setError for each one. React Hook Form puts the message into errors.title, and the form shows it under Title, the same place a browser message would go:

title "   " (3 spaces), Add pressed -> POST requests sent: 1 | messages: {"title":"title is required","author":"","pages":""}
The library form after the server rejected the title. Under the title field a red message says title is required; author is Roald Dahl and pages is 208.
The server's 400 message, placed under Title by setError.

Valid input: 201 Created

The Witches, Roald Dahl, 208. Every rule passes, the generated useCreateBook sends the POST, and the server answers 201 with a Location of /api/books/13 and id 13. onSuccess calls form.reset(), so all three fields are empty again, then invalidates the books query. The list asks the API again and the count goes from 12 to 13:

valid input -> POST requests since: 1 | count on screen: 13 books
form cleared: {"title":"","author":"","pages":""} | messages: {"title":"","author":"","pages":""}

Three submits, side by side

TypedBrowserRequestsServerUnder the field
pages 0fails0(not asked)Too small: expected number to be >0
title of three spacespasses1400title is required
valid bookpasses1201, id 13form cleared, 13 books

The browser check can be skipped by anyone who sends a request directly. Send the same bad body straight to the API with pages 0, and the server still answers 400 with pages must be more than 0. That is why the server check always stays.

Common mistakes

  • Dropping valueAsNumber. Pages arrives as a string and every submit fails with expected number, received string.
  • Trusting the browser check alone. It is for speed. The server's rules are the real gate.
  • Showing server errors in a separate banner. Map the 400's field errors with setError so they land where the user is looking.
  • Hand-editing the generated schema. Change the API, then run npm run api.

Quick recap

PieceJob
CreateBookBodyThe API's own rules, generated from the contract
zodResolver + handleSubmitRuns the rules on submit; onValid only with valid data
registerThe field keeps its value; no render per key
valueAsNumberTurns the field's text into a number
setErrorPuts the server's 400 message under the field
reset + invalidateOn 201, clear the form and refresh the list

Keep going in React · 58 of 59

Previous
A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
Next post
JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Server State With TanStack Query: One Key, One Request, One Cache

Three components need the same list of books. Fetch it by hand and you get three requests; ask TanStack Query for one key and you get one. With real request counts, retries and a quiet refetch on tab focus.

Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache

Add a book with useMutation and let invalidateQueries refetch the list, then make delete instant: snapshot, remove the row in 3 ms, roll back on a 404 and refetch the truth in onSettled.

Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval

Let the API's OpenAPI spec write your React client: Orval turns /v3/api-docs into TypeScript types, useGetBooks and a Zod schema, and a renamed field becomes error TS2339 at BookList.tsx line 26.

A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec

Build the React screen before the API exists: Orval writes MSW handlers and faker data from the spec, a service worker answers GET /api/books inside the browser, and npm run dev:real switches back to the real server.

On this page

  • The rules come from the contract
  • The schema on its own
  • useForm runs the schema
  • register: the field keeps its value
  • valueAsNumber: text becomes a number
  • Stopped in the browser
  • A rule only the server has
  • setError: same field, same place
  • Valid input: 201 Created
  • Three submits, side by side
  • Common mistakes
  • Quick recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.