formik icon indicating copy to clipboard operation
formik copied to clipboard

Formik enters into an endless validation loop when validateOnMount is activated and initialValues change

Open rapzo opened this issue 3 years ago • 7 comments

Bug report

Current Behavior

When using Formik with validateOnMount: true and mutated initialValues controlled outside the form context, on the 1st change, Formik will go into an infinite validation loop, crashing the page eventually. This behavior is easily caught when using a toggle in the form that affects its validation and/or structure.

Expected behavior

It is expected that, whenever initialValues change, a proper validation is done on the newly provided values.

Reproducible example

Formik validateOnMount with a toggle that freezes the app: https://codesandbox.io/s/github/rapzo/formik-validateOnMount/tree/csb-dengj

A possible workaround, although it kind of limits the depth of the changeable value: https://codesandbox.io/s/github/rapzo/formik-validateOnMount/tree/main

Suggested solution(s)

https://github.com/formium/formik/compare/master...rapzo:patch-1

Additional context

I don't know if this was an expected behavior so I'm creating the issue before a PR. Will be happy to add test cases to the PR if this proposal makes sense.

Your environment

Software Version(s)
Formik 2.2.9
React 17.0.2
TypeScript 4.4.2
Browser Google Chrome 91.0.4472.164 (Official Build) (64-bit)
npm/Yarn 6.14.15/1.22.11
Operating System Manjaro (kernel: 5.10.56-1-MANJARO)

rapzo avatar Sep 16 '21 11:09 rapzo

Ran exactly into the same issue... 😉

kevinlandsberg avatar Sep 16 '21 11:09 kevinlandsberg

@kevinlandsberg @rapzo same issue! couldn't figure it out for a while, did you guys find any good solutions? thanks!

onadeemdev avatar Apr 17 '22 18:04 onadeemdev

if you change values, by updating initialValue, you will need to set another property to formik enableReinitialize: true. This way it will work as expected

ktalalykin avatar Apr 21 '22 22:04 ktalalykin

There is a bug that occurs when the initial values is constructed directly inside the parameter object of the use formik function. It recreates the object every time it validates, and every time it creates an object it validates again. The solution was to create this initial values object inside a useEffect.

Example of a case where the problem occurs: image

LeonardoDaLuz avatar Jun 18 '22 14:06 LeonardoDaLuz

if you change values, by updating initialValue, you will need to set another property to formik enableReinitialize: true. This way it will work as expected

This worked! Thanks @ktalalykin .

alexdr00 avatar Mar 21 '23 21:03 alexdr00

Thank you @ktalalykin ! Fixed the issue

eliassaTsb avatar Feb 06 '24 19:02 eliassaTsb