diff --git a/docs/examples/useWatch-selector.tsx b/docs/examples/useWatch-selector.tsx index f74d38c2..15d9cedf 100644 --- a/docs/examples/useWatch-selector.tsx +++ b/docs/examples/useWatch-selector.tsx @@ -9,11 +9,11 @@ type FieldType = { export default () => { const [form] = Form.useForm(); - 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 ( <> -
+ name @@ -22,6 +22,7 @@ export default () => { + values:{JSON.stringify(values)} ); diff --git a/src/useWatch.ts b/src/useWatch.ts index a35888ca..06d2cf90 100644 --- a/src/useWatch.ts +++ b/src/useWatch.ts @@ -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 diff --git a/tests/useWatch.test.tsx b/tests/useWatch.test.tsx index 2c035975..7c97c464 100644 --- a/tests/useWatch.test.tsx +++ b/tests/useWatch.test.tsx @@ -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 ( +
+
+ + + +
+
{nameValue}
+
+ ); + }; + + const { container } = render(); + await act(async () => { + await timeout(); + }); + expect(container.querySelector('.values')?.textContent).toEqual('bamboo'); + const input = container.querySelectorAll('input'); + await changeValue(input[0], 'bamboo2'); + expect(container.querySelector('.values')?.textContent).toEqual('bamboo2'); + }); });