Skip to content

Commit

Permalink
fix: setFieldsValue should tread same as setField (#659)
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ authored Mar 6, 2024
1 parent aacb0e0 commit 02baaae
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,11 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
const namePathMatch = namePathList && containsNamePath(namePathList, namePath);

// `setFieldsValue` is a quick access to update related status
if (info.type === 'valueUpdate' && info.source === 'external' && prevValue !== curValue) {
if (
info.type === 'valueUpdate' &&
info.source === 'external' &&
!isEqual(prevValue, curValue)
) {
this.touched = true;
this.dirty = true;
this.validatePromise = null;
Expand Down
45 changes: 45 additions & 0 deletions tests/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -929,4 +929,49 @@ describe('Form.Basic', () => {
form.setFieldValue('user', null);
});
});

it('setFieldValue should always set touched', async () => {
const EMPTY_VALUES = { light: '', bamboo: [] };
const formRef = React.createRef<FormInstance>();

const Demo: React.FC = () => (
<Form ref={formRef} initialValues={EMPTY_VALUES}>
<Field name="light" rules={[{ required: true }]}>
<Input />
</Field>
<Field name="bamboo" rules={[{ required: true, type: 'array' }]}>
<Input />
</Field>
</Form>
);

render(<Demo />);

await act(async () => {
await formRef.current?.validateFields().catch(() => {});
});
expect(formRef.current?.isFieldTouched('light')).toBeFalsy();
expect(formRef.current?.isFieldTouched('bamboo')).toBeFalsy();
expect(formRef.current?.getFieldError('light')).toHaveLength(1);
expect(formRef.current?.getFieldError('bamboo')).toHaveLength(1);

act(() => {
formRef.current?.setFieldsValue(EMPTY_VALUES);
});
expect(formRef.current?.isFieldTouched('light')).toBeFalsy();
expect(formRef.current?.isFieldTouched('bamboo')).toBeFalsy();
expect(formRef.current?.getFieldError('light')).toHaveLength(1);
expect(formRef.current?.getFieldError('bamboo')).toHaveLength(1);

act(() => {
formRef.current?.setFieldsValue({
light: 'Bamboo',
bamboo: ['Light'],
});
});
expect(formRef.current?.isFieldTouched('light')).toBeTruthy();
expect(formRef.current?.isFieldTouched('bamboo')).toBeTruthy();
expect(formRef.current?.getFieldError('light')).toHaveLength(0);
expect(formRef.current?.getFieldError('bamboo')).toHaveLength(0);
});
});

0 comments on commit 02baaae

Please sign in to comment.