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

fix(useWatch): default value for array of inputs #9555

Merged
merged 2 commits into from Dec 8, 2022
Merged
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
29 changes: 29 additions & 0 deletions src/__tests__/useWatch.test.tsx
Expand Up @@ -92,6 +92,35 @@ describe('useWatch', () => {
expect(result.current).toEqual(['test', 'test1']);
});

it('should return own default value for single input', () => {
const { result } = renderHook(() => {
const { control } = useForm<{ test: string; test1: string }>({});
return useWatch({
control,
name: 'test',
defaultValue: 'test',
});
});

expect(result.current).toEqual('test');
});

it('should return own default value for array of inputs', () => {
const { result } = renderHook(() => {
const { control } = useForm<{ test: string; test1: string }>({});
return useWatch({
control,
name: ['test', 'test1'],
defaultValue: {
test: 'test',
test1: 'test1',
},
});
});

expect(result.current).toEqual(['test', 'test1']);
});

it('should return default value when name is undefined', () => {
const { result } = renderHook(() => {
const { control } = useForm<{ test: string; test1: string }>({
Expand Down
7 changes: 4 additions & 3 deletions src/useWatch.ts
Expand Up @@ -181,9 +181,10 @@ export function useWatch<TFieldValues extends FieldValues>(
});

const [value, updateValue] = React.useState<unknown>(
isUndefined(defaultValue)
? control._getWatch(name as InternalFieldName)
: defaultValue,
control._getWatch(
name as InternalFieldName,
defaultValue as DeepPartialSkipArrayKey<TFieldValues>,
),
);

React.useEffect(() => control._removeUnmounted());
Expand Down