Fix calls to validation with outdated values #939
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Current Behavior
When
handleChange
is called twice without Formik having a chance to rerender/update state in between, the last write to values wins and previous writes are lost for the validation function. Thevalues
state is still correct, butvalidate
will get called with outdated / non-existent values.Assume the initial value is
{ currencyCode: '', amount: '' }
.Then any user-land component code is effectively calling
without Formik having a chance to update in-between.
This leads to the validation running for
instead of
or just
Steps to Reproduce
See steps noted down on https://codesandbox.io/s/40nj93okl9~~The reproduction got a bit longer as I also wanted to illustrate the use-case for it.~~~
I created a simplified version now to make the problem clearer: https://codesandbox.io/s/pk7mk0nny0
Expected behavior
Calling
handleChange
multiple times should not lead to validation with wrong values. The validation should be called with the right values instead.Suggested solution(s)
This happens because of the invalid assumption that
setState
will affect the component state immediately, and the new state will be available onthis.state
immediately - which is a wrong assumption assetState
does not happen immediately.Wait for
setState
to finish before running the validation (as validation usesthis.state
).I opened a PR fixing this: #939
~~CodeSandbox Link: https://codesandbox.io/s/40nj93okl9~~~ longer version
CodeSandbox Link: https://codesandbox.io/s/pk7mk0nny0 simplified version