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

后端 未结 4 1123
难免孤独
难免孤独 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:38

    Formik author here...

    setError was deprecated in v0.8.0 and renamed to setStatus. You can use setErrors(errors) or setStatus(whateverYouWant) in your handleSubmit function to get the behavior you want here like so:

    handleSubmit = async (values, { setErrors, resetForm }) => {
       try {
         // attempt API call
       } catch(e) {
         setErrors(transformMyApiErrors(e))
         // or setStatus(transformMyApiErrors(e))
       }
    }
    
    

    What's the difference use setStatus vs. setErrors?

    If you use setErrors, your errors will be wiped out by Formik's next validate or validationSchema call which can be triggered by the user typing (a change event) or blurring an input (a blur event). Note: this assumed you have not manually set validateOnChange and validateOnBlur props to false (they are true by default).

    IMHO setStatus is actually ideal here because it will place the error message(s) on a separate part of Formik state. You can then decide how / when you show this message to the end user like so.

    // status can be whatever you want
    {!!status && {status}}
    // or mix it up, maybe transform status to mimic errors shape and then ...
    {touched.email && (!!errors.email && {errors.email}) || (!!status && {status.email}) }
    

    Be aware that the presence or value of status has no impact in preventing the next form submission. Formik only aborts the submission process if validation fails.

提交回复
热议问题