Skip to content

Commit 8d2874c

Browse files
committed
chore: warning for dynamic watch namePath.
close ant-design/ant-design#40605
1 parent c3f3e84 commit 8d2874c

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/useWatch.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { FormInstance } from '.';
22
import { FieldContext } from '.';
33
import warning from 'rc-util/lib/warning';
44
import { HOOK_MARK } from './FieldContext';
5-
import type { InternalFormInstance, NamePath, Store } from './interface';
5+
import type { InternalFormInstance, InternalNamePath, NamePath, Store } from './interface';
66
import { useState, useContext, useEffect, useRef, useMemo } from 'react';
77
import { getNamePath, getValue } from './utils/valueUtil';
88

@@ -17,6 +17,19 @@ export function stringify(value: any) {
1717
}
1818
}
1919

20+
const useWatchWarning =
21+
process.env.NODE_ENV !== 'production'
22+
? (namePath: InternalNamePath) => {
23+
const fullyStr = namePath.join('__RC_FIELD_FORM_SPLIT__');
24+
const nameStrRef = useRef(fullyStr);
25+
26+
warning(
27+
nameStrRef.current === fullyStr,
28+
'`useWatch` is not support dynamic `namePath`. Please provide static instead.',
29+
);
30+
}
31+
: () => {};
32+
2033
function useWatch<
2134
TDependencies1 extends keyof GetGeneric<TForm>,
2235
TForm extends FormInstance,
@@ -82,6 +95,8 @@ function useWatch(...args: [NamePath, FormInstance]) {
8295
const namePathRef = useRef(namePath);
8396
namePathRef.current = namePath;
8497

98+
useWatchWarning(namePath);
99+
85100
useEffect(
86101
() => {
87102
// Skip if not exist form instance

tests/useWatch.test.tsx

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,4 +386,25 @@ describe('useWatch', () => {
386386
);
387387
errorSpy.mockRestore();
388388
});
389+
390+
it('dynamic change warning', () => {
391+
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
392+
const Demo: React.FC = () => {
393+
const [form] = Form.useForm();
394+
const [watchPath, setWatchPath] = React.useState('light');
395+
Form.useWatch(watchPath, form);
396+
397+
React.useEffect(() => {
398+
setWatchPath('bamboo');
399+
}, []);
400+
401+
return <Form form={form} />;
402+
};
403+
render(<Demo />);
404+
405+
expect(errorSpy).toHaveBeenCalledWith(
406+
'Warning: `useWatch` is not support dynamic `namePath`. Please provide static instead.',
407+
);
408+
errorSpy.mockRestore();
409+
});
389410
});

0 commit comments

Comments
 (0)