ant-design: Form.useWatch doesn't return initial values
Reproduction link
Steps to reproduce
- Open the reproduction link and browser console there
- You’ll see a log like
form instance: John watcher: undefined
This means John value comes from useFormInstance and undefined comes from useWatch
What is expected?
I’d expect both values to be equivalent
What is actually happening?
useWatch returns undefined value for a field, but in reality it’s defined by Form’s initialValues
| Environment | Info |
|---|---|
| antd | 5.17.3 |
| React | 18 |
| System | Mac OS |
| Browser | Chrome |
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 15 (7 by maintainers)
https://stackblitz.com/edit/react-fpk9br?file=demo.tsx
The initial undefined return from Form.useWatch([], form) is understood. However, there’s a type safety issue for TypeScript users.
When using FormInstance<T>, Form.useWatch([], form) infers the return type as T, but the actual initial return value is undefined. This mismatch bypasses static checks and can lead to runtime errors.
Proposal: Could the TypeScript definition for Form.useWatch([], form) (when used with FormInstance<T>) be updated to return T | undefined?
This would accurately reflect the runtime behavior, enforce safer access patterns (?. / ?? ), and align with similar hooks in other libraries.
Thank you for considering this improvement for TypeScript users.
Using this custom hook which returns the form’s value if
Form.useWatchreturnsundefined.form.getFieldValuedoesn’t trigger a re-render becauseForm.useWatchtriggers it.form.getFieldValuewill only be used for the first render. As mentioned above, from the second render useWatch will give the required watched value.