Currently, Formik doesn't have built in support for passing in an onChange event handler to the form. Specifically, an onChange event handler that would fire any time any of the inputs' data in the formik context change values.
For example, we don't have a handleChange method passed into the Form https://github.com/jaredpalmer/formik/blob/master/packages/formik/src/Form.tsx#L23-L29.
Add support for an onChange event on the <Form>. It would essentially behave the same as the current onChange event on a regular <form>, but would instead fire any time the form data inside Formik updates.
In the current setup, I can't simply pass in an onChange event handler to the <form> element, because it doesn't necessarily always fire when formik input data changes in the formik context.
I briefly poked around the source code. But it would involve creating a handleChange event similar to the handleReset function in https://github.com/jaredpalmer/formik/blob/master/packages/formik/src/Formik.tsx#L863.
All users
P.S. I don't know if you want help with this. I'd be happy to make an attempt at implementing it and make a PR.
-cr
Correct me if I'm wrong, but I believe it already does that. At least from what I could tell, I've been doing exactly what you mentioned to debug changes to the forms. Here's an example project
Or did I misinterpret what you wanted?
Oh cool! ^^ will solve my problem.
It would be nice if we could add support for an onChange prop to the <Formik> component. But your example works for me.
Thanks.
Me too, I need to save form data into my store when form values changes, and re-initialize form after mounting again. e.g: When user go back in the wizard to correct choices and back to current page in react-native using react-navigation-stack. It will unmount current screen when tapping on back button.
On the @osnofa example param of function onChange is the event of the field changed (not all value of the form).
In my case I use a simple Component than listen formik values changes and call function with all values, like that:
export const FormikOnChange = ({ onChange }) => {
const { values } = useFormikContext();
React.useEffect(() => {
onChange(values);
}, [values, onChange]);
return null;
};
~Another use case: re-running form-wide validations on changes to clear any errors. Debatable whether that's better for usability however..~
Actually it turns out I didn't implement form-level validation correctly!
I could see this being needed in situations with multiple forms and shared state. The solution above using useFormikContext works, but it's not straightforward.
Most helpful comment
Oh cool! ^^ will solve my problem.
It would be nice if we could add support for an
onChangeprop to the<Formik>component. But your example works for me.Thanks.