Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/examples/useWatch-selector.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-shadow */
import React from 'react';
import Form, { Field } from 'rc-field-form';
import Input from './components/Input';
Expand All @@ -10,11 +11,15 @@ type FieldType = {

export default () => {
const [form] = Form.useForm<FieldType>();
const firstEmptyObject = Form.useWatch(values => ({ newName: values.name }), form);
console.log('firstEmptyObject', firstEmptyObject);

const values = Form.useWatch(
values => ({ init: values.init, newName: values.name, newAge: values.age }),
{ form, preserve: true },
);
console.log('values', values);

return (
<>
<Form form={form} initialValues={{ init: 'init', name: 'aaa' }}>
Expand Down
8 changes: 5 additions & 3 deletions src/useWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ function useWatch(
const options = isFormInstance(_form) ? { form: _form } : _form;
const form = options.form;

const [value, setValue] = useState<any>();
const [value, setValue] = useState<any>(() =>
typeof dependencies === 'function' ? dependencies({}) : undefined,
);

const valueStr = useMemo(() => stringify(value), [value]);
const valueStrRef = useRef(valueStr);
Expand All @@ -117,8 +119,8 @@ function useWatch(
// ============================= Update =============================
const triggerUpdate = useEvent((values?: any, allValues?: any) => {
const watchValue = options.preserve
? (allValues ?? getFieldsValue(true))
: (values ?? getFieldsValue());
? allValues ?? getFieldsValue(true)
: values ?? getFieldsValue();

const nextValue =
typeof dependencies === 'function'
Expand Down
18 changes: 18 additions & 0 deletions tests/useWatch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -518,4 +518,22 @@ describe('useWatch', () => {
await changeValue(input[0], 'bamboo2');
expect(container.querySelector<HTMLDivElement>('.values')?.textContent).toEqual('bamboo2');
});
it('selector by first no undefined', async () => {
const list: any[] = [];
const Demo = () => {
const [form] = Form.useForm<{ name?: string }>();
const data = Form.useWatch(values => values, form);
list.push(data);
return (
<Form form={form}>
<Field name="name" initialValue="bamboo">
<Input />
</Field>
</Form>
);
};
render(<Demo />);
expect(list[0]).toEqual({});
expect(list[1]).toEqual({ name: 'bamboo' });
});
});