我有这个代码。
export const PostcodeFinder: React.FC = () => {
const {
postcodeSearch,
isLoading,
data,
isPending,
error: fetchError,
} = usePostcodeSearch();
return (
<Formik
validate={(values) => {
// will be ran before the `fetchError` is set from async response
if (fetchError) {
return { postcode: fetchError };
}
return {};
}}
问题是验证称为onChange或在提交表单时使它在异步响应返回之前运行。
如何通过Formik中的异步响应设置验证错误?
答案 0 :(得分:0)
您需要返回一个承诺,该承诺将解决错误对象{ someKey: 'some message' }
<Formik
validate={async (values) => {
const resp = fetch(`/validateEmailExists?email=${values.email}`);
const data = await resp.json();
if (data.emailExists) {
return { email: data.message /* it can be your own custom message */ };
}
return {};
}}