Using undefined for empty input field in react-hook-form

First off: I feel I'm thinking way too complicated here, but can't wrap my brain around it, so here we are:

Let's say I have a schema:
const MySchema = z.object({
  name: z.string(),
  amount: z.number(),
});

I want to build a form with an input type "text" for
name
, and an input type "number" for amount.

Do I need to create an extra "form type" of that schema to represent the data within the form before validation? So something like:
type FormData = {
  name: string;
  amount: number | "";
}


Imo this would make things really complicated since I would need to somewhere (where even?) map my form data to the actual schema data (e.g. amount: formData.amount === "" ? undefined : parseInt(formData.amount),. So yeah, I would like to prevent things like that.

This is why I thought doing fancy things in my FormInput component like
<input
  // ...
  {...register("someProp")}
  onChange={(e) => onChange(transformEventTargetStringValueToActualValueOfWhateverTypeMyPropInTheSchemaHas(e.target.value))}
/>

once would be a good idea. But this also adds
undefined
as a possible value for the input which React doesn't like since changing a component's value between undefined and a defined value makes it switch between being controlled / uncontrolled.

Like I said, I feel I'm thinking way too complicated here. Isn't there an easy solution to handle form input fields' data before validation?
I really don't want to add an additional FormData type for all of my schemas since I'm building lots and lots of forms.
Was this page helpful?