Skip to content

Commit f7e543a

Browse files
committed
feat: api
1 parent 983df60 commit f7e543a

File tree

3 files changed

+45
-3
lines changed

3 files changed

+45
-3
lines changed

docs/demo/useWatch-selector.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
## useWatch-selector
2+
3+
<code src="../examples/useWatch-selector.tsx"></code>

docs/examples/useWatch-selector.tsx

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import React from 'react';
2+
import Form, { Field } from 'rc-field-form';
3+
import Input from './components/Input';
4+
5+
type FieldType = {
6+
name?: string;
7+
age?: number;
8+
};
9+
10+
export default () => {
11+
const [form] = Form.useForm<FieldType>();
12+
const values = Form.useWatch(values => ({ newName: values.name }), form);
13+
console.log('values', values);
14+
return (
15+
<>
16+
<Form form={form}>
17+
name
18+
<Field name="name">
19+
<Input />
20+
</Field>
21+
age
22+
<Field name="age">
23+
<Input />
24+
</Field>
25+
</Form>
26+
</>
27+
);
28+
};

src/useWatch.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,11 @@ function useWatch<TForm extends FormInstance>(
7676
form?: TForm | WatchOptions<TForm>,
7777
): GetGeneric<TForm>;
7878

79+
function useWatch<TForm extends FormInstance, TSelected = unknown>(
80+
selector: (values: GetGeneric<TForm>) => TSelected,
81+
form?: TForm | WatchOptions<TForm>,
82+
): TSelected;
83+
7984
function useWatch<TForm extends FormInstance>(
8085
dependencies: NamePath,
8186
form?: TForm | WatchOptions<TForm>,
@@ -86,8 +91,10 @@ function useWatch<ValueType = Store>(
8691
form?: FormInstance | WatchOptions<FormInstance>,
8792
): ValueType;
8893

89-
function useWatch(...args: [NamePath, FormInstance | WatchOptions<FormInstance>]) {
90-
const [dependencies = [], _form = {}] = args;
94+
function useWatch(
95+
...args: [NamePath | ((values: Store) => any), FormInstance | WatchOptions<FormInstance>]
96+
) {
97+
const [dependencies, _form = {}] = args;
9198
const options = isFormInstance(_form) ? { form: _form } : _form;
9299
const form = options.form;
93100

@@ -126,7 +133,11 @@ function useWatch(...args: [NamePath, FormInstance | WatchOptions<FormInstance>]
126133
const { registerWatch } = getInternalHooks(HOOK_MARK);
127134

128135
const cancelRegister = registerWatch((values, allValues) => {
129-
const newValue = getValue(options.preserve ? allValues : values, namePathRef.current);
136+
const _values = options.preserve ? allValues : values;
137+
const newValue =
138+
typeof dependencies === 'function'
139+
? dependencies(_values)
140+
: getValue(_values, namePathRef.current);
130141
const nextValueStr = stringify(newValue);
131142

132143
// Compare stringify in case it's nest object

0 commit comments

Comments
 (0)