Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Form validate should keep refresh #20725

Merged
merged 2 commits into from Jan 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 44 additions & 0 deletions components/form/__tests__/index.test.js
Expand Up @@ -268,4 +268,48 @@ describe('Form', () => {
'Warning: [antd: Form] antd v4 removed `Form.create`. Please remove or use `@ant-design/compatible` instead.',
);
});

// https://github.com/ant-design/ant-design/issues/20706
it('Error change should work', async () => {
const wrapper = mount(
<Form>
<Form.Item
name="name"
rules={[
{ required: true },
{
validator: (_, value) => {
if (value === 'p') {
return Promise.reject(new Error('not a p'));
}
return Promise.resolve();
},
},
]}
>
<Input />
</Form.Item>
</Form>,
);

/* eslint-disable no-await-in-loop */
for (let i = 0; i < 3; i += 1) {
await change(wrapper, 0, '');
expect(
wrapper
.find('.ant-form-item-explain')
.first()
.text(),
).toEqual("'name' is required");

await change(wrapper, 0, 'p');
expect(
wrapper
.find('.ant-form-item-explain')
.first()
.text(),
).toEqual('not a p');
}
/* eslint-enable */
});
});
8 changes: 8 additions & 0 deletions components/form/util.ts
Expand Up @@ -16,16 +16,24 @@ export function useCacheErrors(
visible: !!errors.length,
});

const [, forceUpdate] = React.useState({});

React.useEffect(() => {
const timeout = setTimeout(() => {
const prevVisible = cacheRef.current.visible;
const newVisible = !!errors.length;

const prevErrors = cacheRef.current.errors;
cacheRef.current.errors = errors;
cacheRef.current.visible = newVisible;

if (prevVisible !== newVisible) {
changeTrigger(newVisible);
} else if (
prevErrors.length !== errors.length ||
prevErrors.some((prevErr, index) => prevErr !== errors[index])
) {
forceUpdate({});
}
}, 10);
return () => clearTimeout(timeout);
Expand Down