Skip to content

Commit 02baaae

Browse files
authored
fix: setFieldsValue should tread same as setField (#659)
1 parent aacb0e0 commit 02baaae

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

src/Field.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,11 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
259259
const namePathMatch = namePathList && containsNamePath(namePathList, namePath);
260260

261261
// `setFieldsValue` is a quick access to update related status
262-
if (info.type === 'valueUpdate' && info.source === 'external' && prevValue !== curValue) {
262+
if (
263+
info.type === 'valueUpdate' &&
264+
info.source === 'external' &&
265+
!isEqual(prevValue, curValue)
266+
) {
263267
this.touched = true;
264268
this.dirty = true;
265269
this.validatePromise = null;

tests/index.test.tsx

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -929,4 +929,49 @@ describe('Form.Basic', () => {
929929
form.setFieldValue('user', null);
930930
});
931931
});
932+
933+
it('setFieldValue should always set touched', async () => {
934+
const EMPTY_VALUES = { light: '', bamboo: [] };
935+
const formRef = React.createRef<FormInstance>();
936+
937+
const Demo: React.FC = () => (
938+
<Form ref={formRef} initialValues={EMPTY_VALUES}>
939+
<Field name="light" rules={[{ required: true }]}>
940+
<Input />
941+
</Field>
942+
<Field name="bamboo" rules={[{ required: true, type: 'array' }]}>
943+
<Input />
944+
</Field>
945+
</Form>
946+
);
947+
948+
render(<Demo />);
949+
950+
await act(async () => {
951+
await formRef.current?.validateFields().catch(() => {});
952+
});
953+
expect(formRef.current?.isFieldTouched('light')).toBeFalsy();
954+
expect(formRef.current?.isFieldTouched('bamboo')).toBeFalsy();
955+
expect(formRef.current?.getFieldError('light')).toHaveLength(1);
956+
expect(formRef.current?.getFieldError('bamboo')).toHaveLength(1);
957+
958+
act(() => {
959+
formRef.current?.setFieldsValue(EMPTY_VALUES);
960+
});
961+
expect(formRef.current?.isFieldTouched('light')).toBeFalsy();
962+
expect(formRef.current?.isFieldTouched('bamboo')).toBeFalsy();
963+
expect(formRef.current?.getFieldError('light')).toHaveLength(1);
964+
expect(formRef.current?.getFieldError('bamboo')).toHaveLength(1);
965+
966+
act(() => {
967+
formRef.current?.setFieldsValue({
968+
light: 'Bamboo',
969+
bamboo: ['Light'],
970+
});
971+
});
972+
expect(formRef.current?.isFieldTouched('light')).toBeTruthy();
973+
expect(formRef.current?.isFieldTouched('bamboo')).toBeTruthy();
974+
expect(formRef.current?.getFieldError('light')).toHaveLength(0);
975+
expect(formRef.current?.getFieldError('bamboo')).toHaveLength(0);
976+
});
932977
});

0 commit comments

Comments
 (0)