DEV Community

Ruben Suet
Ruben Suet

Posted on

Bind properties in a NextJS server action form and useFormState

NextJS suggests you how to bind properties in server actions when working with forms. As well they suggest how to listen to the status of your form once you submit with useFormState. However, how can you bind data AND useFormState together?

The order matters; in this case, you have to bind first, and then wrap it with useFormState.

import { updateServerAction } from './server-actions';

export function UpdateForm({id}: {id: number}) {
  const updateWithId = updateServerAction.bind(null, id)
  const [state, formAction] = useFormState(updateWithId, {
    message: '',

  return (
    <form action={formAction}>
     ... my code
Enter fullscreen mode Exit fullscreen mode

Now when invoking the server action, it can go in the following order:

"use server"

export async function updateServerAction(id: number, prevState: {message: string}, form: FormData) {
  // code
Enter fullscreen mode Exit fullscreen mode

This is quite useful for forms where you need to pass data but you don't want to expose it as hidden fields in the form itself. With this technique now it is possible to listen to the status of the useFormState and pass data to the server without exposing it in the form.

Top comments (0)