jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.98k stars 2.79k forks source link

Initial Errors Resurfaces After Submitting With validateOnMount #3305

Open jacklimwenjie opened 3 years ago

jacklimwenjie commented 3 years ago

Bug report

When validateOnMount is true and the form fails the validation initially, after passing the validation and submit the form, the initial errors are populated again

Current Behavior

Expected behavior

Reproducible example

https://codesandbox.io/s/nostalgic-swirles-vlu5b?file=/src/App.js:581-595

Suggested solution(s)

Additional context

Your environment

Software Version(s)
Formik
React
TypeScript
Browser
npm/Yarn
Operating System
jonatanYanovsky commented 3 years ago

@jacklimwenjie please see my sandbox which shows how to handle this case: https://codesandbox.io/s/formik-debug-validateonmount-jefd4

note that you can force formik to behave properly with

        onSubmit={(values, actions) => {
          actions.setSubmitting(false);
          actions.resetForm({
            values: {
              name: values.name
            }
          });
Valdermeyder commented 2 years ago

I am observing the similar problem but with disappearing of errors when validateOnMount is changed from false to true

I think the route cause of the problem is the part of the code below which ignores the current values of the form and uses initialValues to validate

  React.useEffect(() => {
    if (
      validateOnMount &&
      isMounted.current === true &&
      isEqual(initialValues.current, props.initialValues)
    ) {
      validateFormWithHighPriority(initialValues.current);
    }
  }, [validateOnMount, validateFormWithHighPriority]);