jaredpalmer / formik

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

Validation becomes asynchronous when I use setFieldTouched after setFieldValue in change handler of <input> #2432

Open JJLYHTGP opened 4 years ago

JJLYHTGP commented 4 years ago

❓Question

Seriously, for immediate help, just ask your question on the #formik channel on Reactiflux.

Reproducible example

https://codesandbox.io/s/objective-sun-e6m86?file=/src/App.js

When I use setFieldTouched after setFieldValue, form-level validation become asynchronous, i.e. value changes and error changes after the next render.

When I use setFieldValue after setFieldTouched, value changes and error changes synchronously.

Additional context

https://github.com/jaredpalmer/formik/issues/106#issuecomment-587458116

Your environment

Software Version(s)
Formik ^2.1.4
React ^16.13.0
TypeScript ^3.8.3
Browser Google Chrome 80
npm/Yarn v10.16.0
Operating System macOS 10.15.3
skoging commented 4 years ago

Looks like what you're trying to do is validate on every change, and for that there is the validateOnChange prop on Formik which can simplify this a bit: https://codesandbox.io/s/strange-banzai-8ooxc?file=/src/App.js

There is however an issue with calling setFieldTouched, setTouched, or onBlur immediatly after updating the form values. Due to using state.values here and here, any state change has to be commited (re-rendered) before a call to setFieldTouched, setTouched, or onBlur, otherwise the previous values will be validated instead.

I have this issue with some date pickers where I want to update the value and set the field to touched when a date is selected. My current workaround is an ugly setTimeout to make sure any state changes are re-rendered first.

skoging commented 4 years ago

After reading through #106 this is probably a regression of the same issue after the 2.0 hooks rewrite.

@jaredpalmer Should that issue be reopened or a new bug report filed?

jaredpalmer commented 4 years ago

Separate bug report, with links and references. Thanks