Reputation: 109
I have a form where i am using formik with the validations like
const formik = useFormik({
enableReinitialize: true,
initialValues: {
name: insurer && get(insurer, "name", null),
surname: insurer && get(insurer, "surname", null),
postalCode: insurer && get(insurer, "postalCode", null),
},
onSubmit: (values: any) => {},
validationSchema: Yup.object().shape({
name: Yup.string()
.typeError("Preenche este campo")
.required("Preenche este campo"),
surname: Yup.string()
.typeError("Preenche este campo")
.required("Preenche este campo"),
}),
});
As you can see i have three fields name, surename and postalCode, where i also have defined validation for name and surname, for postalCode, i am hitting an api which is returns false for invalid postalCode
So when initially i submit the form i see error of
Object { surname: "Preenche este campo", name: "Preenche este campo" }
Now if i start typing the postal code i receive error from api and then i set this like
formik.setErrors({postalCode:'error in postal code' });
but now when i console log
console.log(formik.errors)
I only see error for this field, and the other field error are resetted
Object { postalCode: "error in postal code" }
Upvotes: 0
Views: 1955
Reputation: 15520
formik.setErrors
is applied to all errors, {postalCode:'error in postal code' }
is only a particular error of many other errors, so when you set it singularly that has wiped out all other fields' errors.
In this case, you should pass the other fields' errors formik.errors
to that function along with your updated error.
formik.setErrors({ ...formik.errors, postalCode:'error in postal code' });
Upvotes: 1