I am writing a React application and using shadcn as my component library. I am getting this error while trying to render a form . Here is the code for the useFormField hook :
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>");
}
const { id } = itemContext;
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
};
what could be the case here ?
1
i guess the problem is in this line
const fieldState = getFieldState(fieldContext.name, formState);
you are trying to get fieldContext.name but it’s undefined
try to rerrange the order, verify fieldContext before access to its props
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>");
}
const fieldState = getFieldState(fieldContext.name, formState);