Hello all,
I'm currently building out some rather large forms for a project I'm working on.
Using zod to validate the input server-side, I want to be able to return the error(s) to the client to display in the form. Currently, this is done by returning the errors from the server action in an object with the following structure {fieldErrors?: ZodError, ...}. So far so good.
Whenever the user submits a form, it resets. As I understand this is the intended behaviour when using <form action={someAction}>. I have two possible options to overcome this issue:
- Use
onSubmitinstead ofaction, i.e.<form onSubmit={someAction}>
or - Return the request state from within
someAction. I.e. take the form data, parse it into an object and then return this in the error state object. Then usingdefaultValue={state.data?.xyz}I can set the default value for the (uncontrolled) input elements.
Which of the two approaches is more idiomatic/recommended in Next? Especially the second approach seems to be quite clunky and induces some networking overhead (although probably minimal). Additionally I'd be unsure how to handle returning the data from file-inputs.
I'd appreciate some guidance/opinion from a more seasoned Next developer.