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

Can't get correct value through formik.values.fieldName inside the onChange handler #3368

Open
anderlaw opened this issue Oct 6, 2021 · 2 comments

Comments

@anderlaw
Copy link

anderlaw commented Oct 6, 2021

Bug report

export const App = () => {
  const formik = useFormik({
    initialValues: {
      email: 'foobar@example.com'
    },
    onSubmit: (values) => {},
  });
  return <div>
    <input name="email" type="text" value={formik.values.email} onChange={(e)=>{
      formik.handleChange(e);
      console.log('current email:-->',formik.values.email)
    }}/>
  </div>
}

when typing in the input, formik.values.email didn't return the current value of the input box

Current Behavior

image

Expected behavior

formik.values.email should return the current real value

Reproducible example

code sandbox

open the link and check the console tab

Suggested solution(s)

inside the executeChange function(Formik.ts file line 590), update the value in the ctx at the same time.

  const executeChange = React.useCallback(
    (eventOrTextValue: string | React.ChangeEvent<any>, maybePath?: string) => {
  ...
      if (field) {
        // Set form fields by name
        setFieldValue(field, val);
        // update fileds value in context
        ctx.values[field] = val;
      }
    },
    [setFieldValue, state.values]
  );

Additional context

Your environment

Software Version(s)
Formik 2.2.9
React 17.0.2
TypeScript
Browser chrome
npm/Yarn yarn
Operating System macos
@johnrom
Copy link
Collaborator

johnrom commented Oct 6, 2021

This should be fixed in my v3 prototype.

#3231

In my PR you would use formik.getState().values to get the latest state, as the values object associated with the render should be immutable.

@handhikadj
Copy link

handhikadj commented Oct 11, 2021

I'm also experiencing this issue: https://codesandbox.io/s/pedantic-cloud-skr3r at the confirm password validation

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

No branches or pull requests

3 participants