How to properly use Formik's setError method? (React library)

后端 未结 4 1119
难免孤独
难免孤独 2021-02-04 00:26

I am using React communicating with a backend. Now trying to properly implement Formik (Form library).

Main question: How do I properly use Formik\'s setError me

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-04 00:45

    Another way to handle this situation is to assign a specific key to your api errors and use setStatus for status messages.

    __handleSubmit = (values, {setStatus, setErrors}) => {
      return this.props.onSubmit(values)
        .then(() => {
          setStatus("User was updated successfully.");
        })
        .catch((err) => {
          setErrors({api: _.get(err, ["message"])});
        });
    }
    

    Then any validation errors would appear by the fields and any api errors could appear at the bottom:

    
      {({isSubmitting, status, errors, values, setFieldValue}) => (
        
    {errors && _.has(errors, ["api"]) &&
    {_.get(errors, ["api"])}
    } {status &&
    {status}
    }
    )}

    Don't forget about the schema...

    const LoginSchema = Yup.object().shape({
      login: Yup.string()
        .min(4, 'Too Short!')
        .max(70, 'Too Long!')
        .required('Login is required'),
    });
    

    The api error message will show until the next validation call by Formik (i.e. the user is fixing something). But the status message will stay until you clear it (with a timer or Fade).

提交回复
热议问题