'The resetForm method of Formik does not work as expected

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:

  1. user loads a form (with say 2 fields "email" and "address", and initial values: email: "[email protected]", address: "bar"

  2. 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:"[email protected]", 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?



Solution 1:[1]

I would approach this by keeping the original initial values as a reusable variable

const initialValues= { email: '[email protected]' }
<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>

Solution 2:[2]

This modification of Antonio's answer helped me to reset the initialValues.

const genInitialValues = () => ({
  textField: "",
  customField: [],
});

  <Formik
    initialValues={genInitialValues()}
    onSubmit={(values, actions) => {
      ...
      actions.resetForm({ values: genInitialValues() });
    }
  ... />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Matteljay