I’m encountering an issue with Formik’s resetForm()
function triggering the validation schema just before transitioning between screens in a React Native Expo application. Here’s a breakdown of my setup:
I have a handleLogin
function that is invoked upon form submission, which includes the following steps:
const handleLogin = async (
values: LoginValues,
{ setSubmitting, setErrors, resetForm }: FormikHelpers<LoginValues>
) => {
try {
const data = await loginUser(values);
if (data && data.success) {
resetForm(); // <-- Issue arises here
signIn(data.data.token);
await AsyncStorage.setItem("authToken", data.data.token);
await AsyncStorage.setItem("userId", data.data.userId);
navigation.navigate("Home"); // Transition to the home screen
} else {
setErrors({ password: t("invalid-email-or-password") });
}
} catch (error) {
toast.error(t("something-went-wrong"));
} finally {
setSubmitting(false);
}
};
And I’m using Formik for form management with a validation schema defined as follows:
export const useValidationSchemaForLogin = () => {
const { t } = useTranslation();
return Yup.object().shape({
email: Yup.string()
.email(t("enter-valid-email"))
.required(t("email-required")),
password: Yup.string().required(t("password-required")),
});
};
The form itself is rendered using Formik with the useValidationSchemaForLogin schema:
<Formik
initialValues={{ email: "", password: "" }}
onSubmit={handleLogin}
validationSchema={validationSchema}
>
{/* Form fields and submit button */}
</Formik>
I’ve attempted to troubleshoot the issue by reviewing my code logic and researching similar cases online. I expected that calling resetForm() after a successful login would clear the form fields and allow for a smooth transition to the home screen without triggering the validation schema. However, despite my efforts, the validation schema is still triggered during the transition, leading to the brief appearance of the “password-required” error message. I’m seeking guidance on how to resolve this issue effectively.
Tommy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.