With Next.js React Server Component, with no client components, how to show error from Form

214 Views Asked by At

Looking at the example here in the Next.js docs, I want to be able to show the error generated in the Server Action.

Here is the code snippet they show.

Basically, my question is, assume my "mutate data" has a try/catch with the catch having an error, how can I get that data back to the form so the browser user knows that an error occurred and what it was.

I get how to do this with client components, but I'm wanting to do this per this example in the docs.

export default function Page() {
  async function create(formData: FormData) {
    'use server'

    // mutate data
    // revalidate cache
   }
return <form action={create}>...</form>
}
1

There are 1 best solutions below

2
On

This isn't possible right now without using some kind of outside data store (something like redis) to communicate back over.

The useFormState was specifically made to solve this issue of communication from a server action back to a component, and, because it is a hook, it can only be used in a client component.