jaredpalmer / formik

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

Calling setValues twice uses stale data #3846

Closed matomesc closed 10 months ago

matomesc commented 11 months ago

Bug report

Current Behavior

I'm using the callback form of setValues like so to set multiple fields:

setValues(prevValues => {
  return {
    ...prevValues,
    lat: 10,
    lng: 20
  }
);

But when calling it twice prevValues does not update to the new values.

Expected behavior

prevValues should always be updated to the newest values.

Reproducible example

https://codesandbox.io/s/formik-codesandbox-template-forked-whzsh2?file=/index.js

Suggested solution(s)

Additional context

Your environment

Software Version(s)
Formik 2.2.9
React 18.2.0
TypeScript 5.0.4
Browser Chrome 114.0.5735.199
npm/Yarn yarn 3.5.0
Operating System Linux 55bba64d82e6 5.10.102.1-microsoft-standard-WSL2 #1 SMP Wed Mar 2 00:30:59 UTC 2022 x86_64 GNU/Linux
vennilamahalingam commented 11 months ago

I think, setValue returns a promise. I am attaching the codesandbox link with the working code. Updated code - https://codesandbox.io/s/formik-codesandbox-template-forked-f9s8d7?file=/index.js.

Also If you need to update multiple fields, why not send them all at once to setvalues instead of using it twice ?

matomesc commented 11 months ago

It's weird in the docs (https://formik.org/docs/api/formik) and code (https://github.com/jaredpalmer/formik/blob/main/packages/formik/src/types.tsx#L91) the return value of setValues is void. But yes it does seem to return a promise. Maybe the docs / code should be updated to reflect the return of a promise.

DavideFrancescon commented 10 months ago

I can fix the documentation for this. Looking at the function return type it seems like it's miss-matching with the one in the docs, so i'ill change the docs to reflect the one in the return type