new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

Next.js · API reference · all subjects

form handling

5 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

useActionState hook for handling expected errors

Use the useActionState hook to handle expected errors in Server Functions. Instead of using try/catch blocks, model expected errors as return values. The hook returns [state, formAction, pending], where state contains the return value from the Server Function.

Server Action function signature for form submission

A Server Action that receives form data through the form's action prop accepts a 'FormData' parameter. The signature is: `export async function signup(formData: FormData)` in TypeScript or `export async function signup(formData)` in JavaScript. When used with useActionState, the signature becomes: `export async function signup(state: FormState, formData: FormData)` where state is the previous state returned from the action.

useActionState hook for form state management

The useActionState hook from React manages form state and submission. It returns a tuple: `const [state, action, pending] = useActionState(signup, undefined)`. The 'state' contains the returned value from the Server Action (including errors), 'action' is the bound action to pass to the form's action prop, and 'pending' is a boolean indicating if the form is currently submitting. This is used in Client Components ('use client') to display validation errors and manage form submission state.

Form validation with schema libraries

Form fields should be validated on the server using schema validation libraries like Zod, Valibot, or Yup. For example, using Zod: `SignupFormSchema.safeParse({ name: formData.get('name'), email: formData.get('email'), password: formData.get('password') })`. If validation fails, return early from the Server Action with field errors to prevent unnecessary API calls to the authentication provider.

Validate user input in Route Handlers

Validate data before passing it to other systems. Use validation functions to check email, contents, and other user inputs before processing them further.

Give your agent this brain