T
TanStack11mo ago
equal-aqua

Differentiate the type of the field state value and the validation result?

Lets take this example:
const userSchema = z.object({
address: z.object({
street: z.string(),
}),
});

type User = z.infer<typeof userSchema>;

//...

const form = useForm({
defaultValues: {
address: null,
} as unknown as User,
onSubmit: async ({ value }) => {
console.log(value);
},
validatorAdapter: zodValidator(),
validators: {
onChange: userSchema,
},
});
const userSchema = z.object({
address: z.object({
street: z.string(),
}),
});

type User = z.infer<typeof userSchema>;

//...

const form = useForm({
defaultValues: {
address: null,
} as unknown as User,
onSubmit: async ({ value }) => {
console.log(value);
},
validatorAdapter: zodValidator(),
validators: {
onChange: userSchema,
},
});
I would like a field to be initially null and respect this type also during rendering, but after successful validation it's required an therefor the type should omit the null. So basically: - field.state.value should have the type null | { street: string } - value in onSubmit should have the type { address: { street: string } } (omitting the null for address) What's the recommended solution? My usecase is a MUI Autocomplete which is initially empty and omitting the null completely doesn't feel right to me.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?