Skip to content

Commit

Permalink
feat: test
Browse files Browse the repository at this point in the history
  • Loading branch information
crazyair committed Nov 29, 2023
1 parent f7e543a commit 82c6a65
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
5 changes: 3 additions & 2 deletions docs/examples/useWatch-selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ type FieldType = {

export default () => {
const [form] = Form.useForm<FieldType>();
const values = Form.useWatch(values => ({ newName: values.name }), form);
const values = Form.useWatch(values => ({ newName: values.name, newAge: values.age }), form);
console.log('values', values);
return (
<>
<Form form={form}>
<Form form={form} initialValues={{ name: 'aaa' }}>
name
<Field name="name">
<Input />
Expand All @@ -22,6 +22,7 @@ export default () => {
<Field name="age">
<Input />
</Field>
values:{JSON.stringify(values)}
</Form>
</>
);
Expand Down
9 changes: 5 additions & 4 deletions src/useWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,12 @@ function useWatch(
}
});

const _values = options.preserve ? getFieldsValue(true) : getFieldsValue();
// TODO: We can improve this perf in future
const initialValue = getValue(
options.preserve ? getFieldsValue(true) : getFieldsValue(),
namePathRef.current,
);
const initialValue =
typeof dependencies === 'function'
? dependencies(_values)
: getValue(_values, namePathRef.current);

// React 18 has the bug that will queue update twice even the value is not changed
// ref: https://github.com/facebook/react/issues/27213
Expand Down
25 changes: 25 additions & 0 deletions tests/useWatch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -457,4 +457,29 @@ describe('useWatch', () => {

logSpy.mockRestore();
});
it('selector', async () => {
const Demo: React.FC = () => {
const [form] = Form.useForm<{ name?: string }>();
const nameValue = Form.useWatch(values => values.name, form);
return (
<div>
<Form form={form}>
<Field name="name" initialValue="bamboo">
<Input />
</Field>
</Form>
<div className="values">{nameValue}</div>
</div>
);
};

const { container } = render(<Demo />);
await act(async () => {
await timeout();
});
expect(container.querySelector<HTMLDivElement>('.values')?.textContent).toEqual('bamboo');
const input = container.querySelectorAll<HTMLInputElement>('input');
await changeValue(input[0], 'bamboo2');
expect(container.querySelector<HTMLDivElement>('.values')?.textContent).toEqual('bamboo2');
});
});

0 comments on commit 82c6a65

Please sign in to comment.