Dude
Dude

Reputation: 21

Why send formData to a server action on form submission?

I am using NextJS app router and shadcn/ui(uses react-hook-form and zod).

In all the code examples I have seen, the form action receives formData. but in my experience, the formData might not always contains all of the fields and give me some trouble (the solution to this is to add hidden input fields).

So what are the benefits of sending the formData object? and why not just send the form values using form.getValues() via the react-hook-form api and save all of this mess.

export async function serverAction(formData: FormData)

VS

export async function serverAction(data: z.infer<typeof schema>)

Upvotes: 0

Views: 191

Answers (1)

user19259811
user19259811

Reputation:

You're right! You can do either.

FormData:

  • Works without JS as browsers natively support form submissions without js. Hense why form submissions here are server side.
  • Handle file uploads natively (pretty sure)
  • Better nexjs integration. Prefetching / loading / etc. (but this isn't really good argument)
  • Lighter bundle. i.e doesn't need client side validation libs like zod.

RHF + Zod:

  • End to end type safety.
  • Better dev experience-- No need for manual formData parsing in example.
  • Rich Validation-- Meaning you can better validate client to server side with detailed error messages.
  • Better Form State Management especially for large projects.

I often end up using rhf + zod for medium+ sized projects as in terms of long terms dev experience it's much more efficient for me.

For any small projects to get things done, I use next's native form.

Upvotes: 1

Related Questions