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.
Validation should always run with most updated values.
https://codesandbox.io/s/formik-codesandbox-template-gvvqd
Can validation occur inside dispatch?
| Software | Version(s) |
| ---------------- | ---------- |
| Formik | 2.1.2
| React | 16.12.0
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
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
setValuesinstead of multiplesetFieldValue?
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?
Most helpful comment
I'm seeing the same issue as well in 2.1.4