Search code examples
reactjsresetformik

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: "foo@gmail.com", 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:"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?


Solution

  • 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>