Hey I am building a dynamic form with the help of useForm in React. Somehow I have a typescript error I can not fix, even with many example codes and the docs. I built an zod validation file. That looks like that:
import { z } from "zod";
export const PollValidation = z.object({
text: z
.string()
.min(5, { message: "Minimum 5 characters." })
.max(400, { message: "Maximum 400 characters." }),
options: z
.array(
z
.string()
.min(5, { message: "Minimum 5 characters per option." })
.max(400, { message: "Maximum 400 characters per option." })
)
.min(2, { message: "At least 2 options are required." }),
});
and I am using useForm and useFieldArray like that:
const form = useForm<z.infer<typeof PollValidation>>({
resolver: zodResolver(PollValidation),
defaultValues: {
text: poll ? poll?.text : "",
options: ["Option 1", "Option 2"]
},
});
const { fields, append, remove } = useFieldArray<
z.infer<typeof PollValidation>
>({
control: form.control,
name: "options" as const,
});
Actually the code and my form is running as expected but when i set the name for the field array:
name: "options" as const,
I am getting this error:
Type '"options"' is not assignable to type 'never'.
fieldArray.d.ts(6, 5): The expected type comes from property 'name' which is declared here on type 'UseFieldArrayProps<{ text: string; options: string[]; }, never, "id">'
Thanks for any help :)
Unfortunately useFieldArray
supports only arrays of objects. If you change options to object array it will work:
export const PollValidation = z.object({
options: z
.array(
z.object({
value: z.string()
})
)
})
You can also find this issue on their github