I'm using Formik
in my application and I want to cancel changes made to a form and revert it to its initial values (this is not about clearing form after submit, which is what most tutorials and issues are about).
Here is a simple use case:
user loads a form (with say 2 fields "email" and "address", and initial values: email: "foo@gmail.com", address: "bar"
user starts editing the email field. But then he decide to cancel the changes made and to revert to initial values (meaning "foo@gmail", "bar").
const MyForm = () => (
<Formik initialValues={{ email:"foo@gmail.com", address: "bar" })>
...
</Formik>
)
I use the resetForm
. But it does not revert my form to its initial values
const ResetButtom = () => {
const { resetForm } = useFormikContext();
return (
<Button onClick={() => resetForm()} {...} />
Reset
</Button>
)
}
How can I achieve this functionality with Formik?
I would approach this by keeping the original initial values as a reusable variable
const initialValues= { email: 'foo@email.com' }
<Formik initialValues={initialValues} ... />
and then:
<Button onClick={() => resetForm(initialValues)} {...} />
Reset
</Button>
If you are using Formik v2:
<Button onClick={() => resetForm({ values: initialValues })} {...} />
Reset
</Button>
Alternatively, you can use setValues
in the similar manner:
<Button onClick={() => setValues({ ...initialValues })} {...} />
Reset
</Button>