@@ -76,6 +76,18 @@ function useWatch<TForm extends FormInstance>(
76
76
form ?: TForm | WatchOptions < TForm > ,
77
77
) : GetGeneric < TForm > ;
78
78
79
+ // ------- selector type -------
80
+ function useWatch < TForm extends FormInstance , TSelected = unknown > (
81
+ selector : ( values : GetGeneric < TForm > ) => TSelected ,
82
+ form ?: TForm | WatchOptions < TForm > ,
83
+ ) : TSelected ;
84
+
85
+ function useWatch < ValueType = Store , TSelected = unknown > (
86
+ selector : ( values : ValueType ) => TSelected ,
87
+ form ?: FormInstance | WatchOptions < FormInstance > ,
88
+ ) : TSelected ;
89
+ // ------- selector type end -------
90
+
79
91
function useWatch < TForm extends FormInstance > (
80
92
dependencies : NamePath ,
81
93
form ?: TForm | WatchOptions < TForm > ,
@@ -86,8 +98,10 @@ function useWatch<ValueType = Store>(
86
98
form ?: FormInstance | WatchOptions < FormInstance > ,
87
99
) : ValueType ;
88
100
89
- function useWatch ( ...args : [ NamePath , FormInstance | WatchOptions < FormInstance > ] ) {
90
- const [ dependencies = [ ] , _form = { } ] = args ;
101
+ function useWatch (
102
+ ...args : [ NamePath | ( ( values : Store ) => any ) , FormInstance | WatchOptions < FormInstance > ]
103
+ ) {
104
+ const [ dependencies , _form = { } ] = args ;
91
105
const options = isFormInstance ( _form ) ? { form : _form } : _form ;
92
106
const form = options . form ;
93
107
@@ -125,8 +139,15 @@ function useWatch(...args: [NamePath, FormInstance | WatchOptions<FormInstance>]
125
139
const { getFieldsValue, getInternalHooks } = formInstance ;
126
140
const { registerWatch } = getInternalHooks ( HOOK_MARK ) ;
127
141
142
+ const getWatchValue = ( values : any , allValues : any ) => {
143
+ const watchValue = options . preserve ? allValues : values ;
144
+ return typeof dependencies === 'function'
145
+ ? dependencies ( watchValue )
146
+ : getValue ( watchValue , namePathRef . current ) ;
147
+ } ;
148
+
128
149
const cancelRegister = registerWatch ( ( values , allValues ) => {
129
- const newValue = getValue ( options . preserve ? allValues : values , namePathRef . current ) ;
150
+ const newValue = getWatchValue ( values , allValues ) ;
130
151
const nextValueStr = stringify ( newValue ) ;
131
152
132
153
// Compare stringify in case it's nest object
@@ -137,10 +158,7 @@ function useWatch(...args: [NamePath, FormInstance | WatchOptions<FormInstance>]
137
158
} ) ;
138
159
139
160
// TODO: We can improve this perf in future
140
- const initialValue = getValue (
141
- options . preserve ? getFieldsValue ( true ) : getFieldsValue ( ) ,
142
- namePathRef . current ,
143
- ) ;
161
+ const initialValue = getWatchValue ( getFieldsValue ( ) , getFieldsValue ( true ) ) ;
144
162
145
163
// React 18 has the bug that will queue update twice even the value is not changed
146
164
// ref: https://github.com/facebook/react/issues/27213
0 commit comments