Formik: Validation run on obsolete data when calling setFieldValue multiple times consecutively

Created on 3 Feb 2020  路  10Comments  路  Source: formium/formik

馃悰 Bug report

Current Behavior

When setFieldValue is called multiple times consecutively, before Formik's inner dispatch finishes updating the state in between, validation reflects only the last write.

For example, assume the initial values is { x: '', y: '', z: '' } and all are required, calling:

setFieldValue('x', 1);
setFieldValue('y', 2);
setFieldValue('z', 3);

The validation function will run on the following objects:

{ x: '1', y: '', z: '' }
{ x: '', y: '2', z: '' }
{ x: '', y: '', z: '3' }

And the resulting values will be { x: '1', x: '2', z: '3' } while errors will be { 'x': 'Required', 'y': 'Required' }.

The issue reproduces if setFieldValue is followed by setFieldTouched.

Expected behavior

Validation should always run with most updated values.

Reproducible example

https://codesandbox.io/s/formik-codesandbox-template-gvvqd

Suggested solution(s)

Can validation occur inside dispatch?

Your environment

| Software | Version(s) |
| ---------------- | ---------- |
| Formik | 2.1.2
| React | 16.12.0

Most helpful comment

I'm seeing the same issue as well in 2.1.4

All 10 comments

2.1.3 with similar issue here - https://codesandbox.io/s/formik-codesandbox-template-9k3i2
1.5.8 is working as it should be - http://codesandbox.io/s/formik-codesandbox-template-j0gmu

I confirm the same behavior on 2.1.4

Seem to be introduced in 2.0.1-rc11.

I'm seeing the same issue as well in 2.1.4

I believe Im having the same problem here...
Im running validateForm manually but it validates the form with the previous value instead of the actual one.
Also I saw it was calling my validation twice, first with my value and then with undefined
When running it inside a setTimeout it doest work tho

In my case I managed to fix it by passing the current value to validateForm to be validated properly.

I believe it can be the same problem as yours

I run into this same issue.
Currently, my solution is to call validation one more time in 'useEffect' ( make sure 'values' is the latest).

Same issue here, but shouldn't we actually use setValues instead of multiple setFieldValue ?

Same issue here, but shouldn't we actually use setValues instead of multiple setFieldValue ?

I'm also having this problem. Calling setValues will delete any value that isn't passed to it in the fields object though.

My temporary workaround is to wrap all setFieldValue in setTimeout:

onChange={() => {
  setTimeout(() => {
    setFieldValue('shareData', !values.shareData)
  }, 0)
}}

I am having the same problem. Any update on this?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Jucesr picture Jucesr  路  3Comments

jaredpalmer picture jaredpalmer  路  3Comments

ancashoria picture ancashoria  路  3Comments

jaredpalmer picture jaredpalmer  路  3Comments

najisawas picture najisawas  路  3Comments