Skip to content

fix: Fix the issue of useWatch name being undefined returning {} #690

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

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/useWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ function useWatch(
const { registerWatch } = getInternalHooks(HOOK_MARK);

const getWatchValue = (values: any, allValues: any) => {
if (dependencies === undefined) {
return undefined;
}
const watchValue = options.preserve ? allValues : values;
return typeof dependencies === 'function'
? dependencies(watchValue)
Expand Down
28 changes: 28 additions & 0 deletions tests/useWatch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,34 @@ describe('useWatch', () => {
expect(container.querySelector<HTMLDivElement>('.values')?.textContent).toEqual('bamboo');
});

it('undefined', async () => {
const Demo = ({ name }: { name?: string }) => {
const [form] = Form.useForm();
const nameValue = Form.useWatch(name, form);
return (
<div>
<Form form={form} initialValues={{ name: 'bamboo', other: 'other' }}>
<Field name="name">
<Input />
</Field>
</Form>
<div className="values">{nameValue}</div>
</div>
);
};

const { container, rerender } = render(<Demo />);
await act(async () => {
await timeout();
});
expect(container.querySelector<HTMLDivElement>('.values')?.textContent).toEqual('');
rerender(<Demo name="" />);
await act(async () => {
await timeout();
});
expect(container.querySelector<HTMLDivElement>('.values')?.textContent).toEqual('');
});

it('change value with form api', async () => {
const staticForm = React.createRef<FormInstance>();
const Demo: React.FC = () => {
Expand Down