使用Formik处理来自API的错误 [英] Handling errors from api with Formik

查看:126
本文介绍了使用Formik处理来自API的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从api中捕获错误,并以表格形式显示它们,并且工作正常.但是问题是,当我以一种形式更改一个字段时,所有错误都消失了.对于表单,我使用的是Formik,并用于验证.

I am catching errors from api and showing them in form, and that is working fine. But the problem is when I change one field in form all errors disappear. For form I am using Formik and for validation Yup.

const handleSubmit = (values, {setSubmitting,  setFieldError, setStatus}) => {
    someApiCall(values)
        .then(
            () => {

            },
            (error) => {
                // example of setting error
                setFieldError('email', 'email is already used');
            })
        .finally(() => {
            setSubmitting(false)
        });
};

我尝试在setFieldError中添加第三个参数false,但没有任何改变.

I tried with adding third parametar false to setFieldError, but nothing changed.

推荐答案

这是我的工作示例: Formik中提供了一个回调validate: https://jaredpalmer.com/formik/docs/api/formik#validate-values-values-formikerrors-values-promise-any ,您可以尝试使用以下方法进行操作.

There's a callback validate available in Formik: https://jaredpalmer.com/formik/docs/api/formik#validate-values-values-formikerrors-values-promise-any using which you can probably try to do something like below.

我用空数组启动了emailsAlreadyInUse,然后在您的API调用中返回错误,然后将该用户添加到该数组中,并且一旦用户再次使用同一封电子邮件并尝试进行验证,尽管它将通过Yup验证,但它将被困在validate回调中,我相信它会在Yup验证后运行(尽管我可能错了,但在您的情况下没关系).

I initiated emailsAlreadyInUse with empty array and then in your API call once error gets returned then add that user to the array and once user uses the same email again and tried to validate, although it will pass Yup validation but it will be caught in validate callback which I believe runs after Yup validation (though I could be wrong but in your case doesn't matter).

const emailsAlreadyInUse= [];
const handleSubmit = (values, {
  setSubmitting,
  setFieldError,
  setStatus
}) => {
  someApiCall(values)
    .then(
      () => {
        // Do something
        // possibly reset emailsAlreadyInUse if needed unless component is going to be unmounted.
      },
      (error) => {
        // example of setting error
        setFieldError('email', 'email is already used');
        // Assuming error object you receive has data object that has email property
        emailsAlreadyInUse.push(error.data.email);
      })
    .finally(() => {
      setSubmitting(false)
    });
};

<Formik
...
...
validate = {
  values => {
    let errors = {};
    if (emailsAlreadyInUse.includes(values.email)) {
      errors.email = 'email is already used';
    }
    return errors;
  }
}
/>

这篇关于使用Formik处理来自API的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆