Skip to content

Commit

Permalink
馃悶 fix(useWatch): default value for array of inputs (#9555)
Browse files Browse the repository at this point in the history
* fix(useWatch): default value for array of inputs

* Update useWatch.ts

Co-authored-by: Beier (Bill) <bluebill1049@hotmail.com>
  • Loading branch information
adesurirey and bluebill1049 committed Dec 8, 2022
1 parent c21210b commit f3f9e2d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
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

0 comments on commit f3f9e2d

Please sign in to comment.