Skip to content

Commit

Permalink
chore: improve error when not passing control to useController
Browse files Browse the repository at this point in the history
  • Loading branch information
MeLlamoPablo committed Oct 24, 2023
1 parent dd89833 commit 339f925
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
20 changes: 20 additions & 0 deletions src/__tests__/useController.test.tsx
Expand Up @@ -840,4 +840,24 @@ describe('useController', () => {
screen.getByText('disable');
});
});

it("should throw a meaningful error if the control prop isn't passed", async () => {
const Component = () => {
useController({
name: 'test',
defaultValue: '',
});

return null;
};

// Don't log the thrown error to the console
const spy = jest.spyOn(console, 'error').mockImplementation();

expect(() => render(<Component />)).toThrow(
'useController: missing `control`. Pass `control` as a prop or provide it via FormProvider.',
);

spy.mockRestore();
});
});
14 changes: 13 additions & 1 deletion src/useController.ts
Expand Up @@ -53,7 +53,19 @@ export function useController<
props: UseControllerProps<TFieldValues, TName>,
): UseControllerReturn<TFieldValues, TName> {
const methods = useFormContext<TFieldValues>();
const { name, disabled, control = methods.control, shouldUnregister } = props;
const {
name,
disabled,
control = methods?.control,
shouldUnregister,
} = props;

if (!control) {
throw new Error(
'useController: missing `control`. Pass `control` as a prop or provide it via FormProvider.',
);
}

const isArrayField = isNameInFieldArray(control._names.array, name);
const value = useWatch({
control,
Expand Down

0 comments on commit 339f925

Please sign in to comment.