jaredpalmer / formik

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

Multiple calls to setFieldValue inside async action result in form errors #3754

Open matt-sanders opened 1 year ago

matt-sanders commented 1 year ago

Bug report

Current Behavior

We have a use case where fields need to be updated as the result of an async function, very similar to this example. However, we would like to update multiple fields. We find that when we use setValues things work as expected, however when we make multiple calls to setFieldValue it results in an error.

This doesn't happen if the calls to setFieldValue happen as an immediate callback ( e.g. from a button ) but when the callback happens after an async action, things go a little awry.

The obvious, initial solution is to just use setValues, but we may want to update these fields individually given certain circumstances ( e.g. if x, then update y but not z )

Expected behavior

Multiple calls to setFieldValue should not trigger validation errors when the form is valid.

Reproducible example

Live example: https://d4pe7b.csb.app/

Codesandbox: https://codesandbox.io/s/proud-wind-d4pe7b?file=/src/App.js

Your environment

Software Version(s)
Formik 2.2.9
React 18.2.0
TypeScript -
Browser Chrome
npm/Yarn npm
Operating System MacOS
3nvi commented 1 year ago

Yup, validated this today as well.

It's because each setFieldValue call doesn't take into account any updated values through other calls.

Thus if you have 2 back-to-back setFieldValue , they both use the same snapshot of values without the 2nd setFieldValue factoring in the updates of the 1st setFieldValue call.

LaikaTheSpaceDog commented 1 year ago

I was having a similar issue and can confirm that my bug was caused by what @3nvi has described above 👍

matt-sanders commented 1 year ago

Ok, so is there any solution to that? I would have thought that awaiting the promise from setFieldValue should cause the next one to use the correct values. Kind of like how setState would work when passing a function as the callback.

VizTheWiz commented 2 months ago

Encountered this exact issue today, with version 2.4.5, on chrome / Ubuntu / react 18.2. At least I was able to fix this with setValues, but I would have expected that awaiting a setFieldValue call would ensure the state is correctly updated upon continuation.

abhinavkumar940 commented 2 months ago

Can confirm this on v 2.4.6 as of today. Also as @VizTheWiz suggested, setValues helps.