Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: improve error when not passing control to useController #11028

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/__tests__/useController.test.tsx
Expand Up @@ -1012,4 +1012,24 @@ describe('useController', () => {
}),
);
});

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