formik icon indicating copy to clipboard operation
formik copied to clipboard

Fix validation on stale values

Open Jestermaxrko opened this issue 6 months ago • 8 comments

Fixes issue - https://github.com/jaredpalmer/formik/issues/2083

The cause of the issue is in this line https://github.com/jaredpalmer/formik/blob/0f960aaeeb0bdbef8312b5107cd3374884a0e62b/packages/formik/src/Formik.tsx#L185

beause of assigning value from stateRef.current to the state variable this variable contains "old" value until next re-render https://github.com/jaredpalmer/formik/blob/0f960aaeeb0bdbef8312b5107cd3374884a0e62b/packages/formik/src/Formik.tsx#L190

And then when setFieldValue and setFieldTouched are called consecutively stateRef.current references to updated value imediatelly after setFieldValue call, but state variable is still references to the old value and setFieldTouched runs validation on that old value

Using stateRef.current directly gurantees that actual values are taken

Jestermaxrko avatar Jan 25 '24 17:01 Jestermaxrko

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
formik-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 11, 2024 10:40pm

vercel[bot] avatar Jan 25 '24 17:01 vercel[bot]

🦋 Changeset detected

Latest commit: e004b643077cd54ff52ad4b18ddb6001ebe87d2b

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
formik Patch
formik-native Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

changeset-bot[bot] avatar Jan 25 '24 17:01 changeset-bot[bot]

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

codesandbox-ci[bot] avatar Jan 25 '24 17:01 codesandbox-ci[bot]

Helpful change. Are we pending one more review to get this merged?

ypk4 avatar Mar 05 '24 16:03 ypk4

Thank you very much. I hope it will be released.

pvcresin avatar Mar 19 '24 02:03 pvcresin

Would love a test please

quantizor avatar Apr 10 '24 17:04 quantizor

I think I see some of the source of confusion, in Formik.tsx stateRef.current is saved to state but the issue is that ref is wholly-replaced inside of dispatch. We should probably remove that variable altogether because it is a quiet source of bugs.

https://github.com/jaredpalmer/formik/blob/c6ceb654761c268fdc76b225f31453dd4dec1be6/packages/formik/src/Formik.tsx#L185

quantizor avatar Apr 10 '24 18:04 quantizor

Any chance this can get merged and released? Seems like a helpful change to keep on the shelf.

gone-skiing avatar Jun 05 '24 15:06 gone-skiing