jaredpalmer / formik

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

Revalidate form if validationSchema on prop change #2668

Open yekver opened 4 years ago

yekver commented 4 years ago

🐛 Bug report

Current Behavior

right now if validationSchema prop changed form wouldn't revalidate

Expected behavior

form should run validation on every validationSchema prop change

Your environment

Software Version(s)
Formik 2.1.5
React 16.13.1
TypeScript 3.9.7
Browser Chrome
npm/Yarn npm
Operating System windows
github-actions[bot] commented 4 years ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days

yekver commented 4 years ago

ping

johnrom commented 4 years ago

That's reasonable. The only issue I see with it is that some people may regenerate the validationSchema on every render, causing validation on every render, which might cause a state update and thus an infinite loop.

I think we only apply a new errors object if it isn't the same as the old, so the infinite loop condition may not occur.

github-actions[bot] commented 3 years ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days

github-actions[bot] commented 3 years ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days

yekver commented 3 years ago

up

lexanth commented 3 years ago

As a workaround, I've mounted this component inside the form:

const RevalidateOnSchemaChange = ({ validationSchema }) => {
  const { validateForm } = useFormikContext();
  useEffect(() => {
    validateForm();
  }, [validationSchema, validateForm]);
  return null;
};

Could be a custom hook etc, but I wanted it inside the Formik render callback

rgallison commented 2 years ago

Just ran into this myself. Great workaround @lexanth

fjbotto commented 2 months ago

@lexanth or @rgallison how do you actually update the validationSchema to formik? How do you send the new schema?

rgallison commented 2 months ago

@fjbotto You just change whatever you are passing into the validation

For example, the following is a pretty common pattern:

const [isDraft, setIsDraft] = useState(true)
let schema = isDraft ? schemaA : schemaB;

const handleSubmit= () => setIsDraft(false);

return <Formik onSubmit={handleSubmit} validationSchema={schema}>...</Formik>