formik
formik copied to clipboard
resetForm() doesn't reset form
Bug report
Current Behavior
I'm using the <Formik> component wrapper and in a nested component the useFormikContext() hook. When calling the resetForm() method from useFormikContext, it doesn't actually reset the touched, errors or values to initialValues set in the <Formik> wrapper. I have to call setTouched(), setError() and setValues() individually to achieve the result expected.
Expected behavior
When calling resetForm() the <Formik> state is reset to the initialized values.
Reproducible example
Tried using the above sandbox however useFormikContext() was throwing an error (not a method of formik)
Your environment
Software | Version(s) |
---|---|
Formik | "^2.2.9" |
React | "18.2.0", |
TypeScript | n/a |
Browser | chrome & brave |
npm/Yarn | 8.19.2 |
Operating System | macOS Ventura |
Do you have a reproduction sandbox?
I am experiencing a similar issue in my codebase. it was working fine with React 17 but the upgrade to React 18 broke this behaviour.
Update:
I could fix it by using flushSync
from react-dom
flushSync(() => {
resetForm();
});
I am not able to reproduce the issue. Refer : https://codesandbox.io/s/formik-v2-useformikcontext-forked-pc6j9g?file=/index.js Or can you make changes in this sandbox with the exact use case as yours ?
<Formik initialValues={initialValues} onSubmit={(data, params) => { console.log(data); addProduct(data); params.resetForm(); }} validationSchema={validationSchema} >