How can I allow null form values but non-null submission values? (Typescript, MUI, Controller, Autocomplete) #9332
Replies: 7 comments 6 replies
|
Could you please explain more details what problem you got with the codesandbox url ? |
|
@tomashaddad You can use "onError" callback of method |
|
Hello, I have the same problem. Here is a simple code to demonstrate it. |
|
Late to the party I guess but for what it's worth, useForm nowadays supports passing a TTransformedValues generic: |
|
Hello @tomashaddad , did you find a good solution for this case? |
|
to add to @BrendanC23 answer, here is a small utility function to add a nullable input but keep the required output: |
|
The clean type-level answer is to separate the form's input type from its submit/output type. React Hook Form supports this with the third generic, type FormInput = {
name: string | null
}
type FormOutput = {
name: string
}
const form = useForm<FormInput, unknown, FormOutput>({
defaultValues: { name: null },
resolver,
})
const onSubmit: SubmitHandler<FormOutput> = (data) => {
data.name // string
}If you are using Zod, make the schema accept nullable input but output non-null: const schema = z.object({
name: z.string().nullable().pipe(z.string().min(1)),
})
type FormInput = z.input<typeof schema> // string | null
type FormOutput = z.output<typeof schema> // string
const form = useForm<FormInput, unknown, FormOutput>({
resolver: zodResolver(schema),
defaultValues: { name: null },
})That matches the UI reality: MUI Autocomplete needs |
Uh oh!
There was an error while loading. Please reload this page.
Hi,
Firstly, thank you a lot for this package!
I've searched around a bit for this but I'm still not sure how to do it properly. Take this example with two codependent MUI
Autocompletecomponents:https://codesandbox.io/s/elastic-sanne-2cck6p?file=/src/App.tsx
Autocompletetakes a value ofnullto display no item. This is the default behaviour I want since this data will come from a server. Submission of this form is not possible without both fields, but the submit function expects the type of the submission to match the type of the form.So if form submission is successful, how can I write a submit function that knows the given values aren't null?
Thank you!
All reactions