简体   繁体   中英

Show API error on formik like yup message error

I wrote this code to create a login form using formik and yup . Now, I'm trying to handle the error from the login API but I don't find any usefull example or guide. There is a universal method for handling all possibile API error based on the fields defined on the initialValues fields of Formik components or the yup schema?

This is my custom InputText that just handle the yup error:

export default function InputText({fieldName, noTop, ...props}) {

  const [field, meta] = useField(fieldName);

  return (
    <React.Fragment>
      <TextInput
        style={[styles.input, {marginTop: noTop ? 0 : 20}]}
        value={field.value}
        onChangeText={field.onChange(fieldName)}
        onBlur={field.onBlur(fieldName)}
        {...props}
      />
      {meta.error && meta.touched && (
        <Text style={styles.error}>{meta.error}</Text>
      )}
    </React.Fragment>
  );
}

And this is the code of the Login form:

<Formik
  validationSchema={loginValidator}
  initialValues={{
    username: '',
    password: '',
  }}
  onSubmit={ async (values) => login(JSON.stringify(values)) }
>
  <LoginBody/>
</Formik>

The LoginBody is the body of the login form, that is create using useFormikContext() . Its contain two InputText : username , password ; and a button that, onPress call submitForm .

You can call setFieldError inside onSubmit function.

As you can see in the docs the second parameter of onSubmit is the formikbag and you can get setFieldError from it.

onSubmit={async (values, { setFieldError }) => {
    // do what you need to do
    // get the field and the error from the api call
    // set the error message for that field
    setFieldError(fieldName, errorMessage)
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM