Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix calls to validation with outdated values #939

Merged
merged 1 commit into from
Sep 28, 2018
Merged

Fix calls to validation with outdated values #939

merged 1 commit into from
Sep 28, 2018

Conversation

dferber90
Copy link
Contributor

@dferber90 dferber90 commented Sep 26, 2018

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. The values state is still correct, but validate will get called with outdated / non-existent values.

Assume the initial value is { currencyCode: '', amount: '' }.

Then any user-land component code is effectively calling

handleChange({ target: { name: "currencyCode", value: "EUR" } })
handleChange({ target: { name: "amount", value: "3" } })

without Formik having a chance to update in-between.

This leads to the validation running for

{ currencyCode: "EUR", amount: "" }
{ currencyCode: "", amount: "3" }

instead of

{ currencyCode: "EUR", amount: "" }
{ currencyCode: "EUR", amount: "3" }

or just

{ currencyCode: "EUR", amount: "3" }

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 on this.state immediately - which is a wrong assumption as setState does not happen immediately.

Wait for setState to finish before running the validation (as validation uses this.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


  • Formik Version: 1.3.0
  • React Version: 16.5.2
  • TypeScript Version:
  • Browser and Version:
  • OS:
  • Node Version:
  • Package Manager and Version:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants