I try to set an error message to a field, when submitting the form results in an error. I use the useFormik. The Structure is like
InterfaceType : {
names:[TranslationInterface]
}
TranslationInterface : {
language: ENUM,
value: ""
}
const formik = useFormik({
initialValues: {},
onSubmit: async (value: InterfaceType, { setSubmitting, setFieldError,setErrors }) => {
try {
//api call which leads to an exception
} catch (e: unknown) {
console.log(e); // got here
const errors: FormikErrors<any> = {}
for (const error of e.validationErrorData) {
if (typeof error.parameterName === "string" && getIn(formik.values,error.parameterName) !== undefined) {
//path exists in formik.values
const key = error.parameterName;
setFieldError(key, error.message); // setting each field seems not to work
errors[key as keyof Ingredient] = error.message.substring(error.message.indexOf("validation error:"));
}
}
setErrors(errors);
console.log(formik.errors); // still empty
} finally {
setSubmitting(false);
}
}
});
My field looks like
<TextField
key={"field_" + translation.language + "_" + index}
name={"names[" + index +"].value"}
label={t("INGREDIENT_DETAIL_FIELD_NAME_" + translation.language)}
readonly={viewModus=== ViewModus.OPEN}
onChange={formik.handleChange}
value={formik.values.names!.at(index)!.value!}
errorMessage={getIn(formik.errors,"names[" + index +"].value")}>
</TextField>
The values got added to the formik.values correctly and the formik.handleChange also works. But the error message does not get displayed. The formik.errors seems to stay empty. Whether I use the setErrors or the setFieldError Method.