()
| 43 | }; |
| 44 | |
| 45 | const useFormField = () => { |
| 46 | const fieldContext = React.useContext(FormFieldContext); |
| 47 | const itemContext = React.useContext(FormItemContext); |
| 48 | const { getFieldState } = useFormContext(); |
| 49 | const formState = useFormState({ name: fieldContext.name }); |
| 50 | |
| 51 | // Both contexts default to {} (a truthy value), so guard on the field that |
| 52 | // each provider actually supplies, and do it before any value is consumed. |
| 53 | if (!fieldContext.name) { |
| 54 | throw new Error("useFormField should be used within <FormField>"); |
| 55 | } |
| 56 | |
| 57 | if (!itemContext.id) { |
| 58 | throw new Error("useFormField should be used within <FormItem>"); |
| 59 | } |
| 60 | |
| 61 | const fieldState = getFieldState(fieldContext.name, formState); |
| 62 | const { id } = itemContext; |
| 63 | |
| 64 | return { |
| 65 | id, |
| 66 | name: fieldContext.name, |
| 67 | formItemId: `${id}-form-item`, |
| 68 | formDescriptionId: `${id}-form-item-description`, |
| 69 | formMessageId: `${id}-form-item-message`, |
| 70 | ...fieldState |
| 71 | }; |
| 72 | }; |
| 73 | |
| 74 | type FormItemContextValue = { |
| 75 | id: string; |
no outgoing calls
no test coverage detected