Formik - How to reset form after confirmation Formik - How to reset form after confirmation reactjs reactjs

Formik - How to reset form after confirmation


Hello @Aximili you can use resetForm in onSubmit.

onSubmit={(values, { resetForm }) => {      // do your stuff       resetForm();}}

what resetForm can do?

Imperatively reset the form. This will clear errors and touched, set isSubmitting to false, isValidating to false, and rerun mapPropsToValues with the current WrappedComponent's props or what's passed as an argument. The latter is useful for calling resetForm within componentWillReceiveProps.


If using useFormik hook then use formik.resetForm() on onClick event or if you are using <Formik> component than you can do like this:

onSubmit={(values, { setSubmitting, resetForm }) => {    // your code    resetForm();}}


I'm not completely certain, but I think you will have to write your own reset function without a button with a reset type. Something like this:

const handleReset = (resetForm) => {  if (window.confirm('Reset?')) {    resetForm();  }};function Example() {  return (    <Formik initialValues={{ value: 1 }}>      {formProps => {        return (          <Form>            <Field name="value" type="number" />            <button              onClick={handleReset.bind(null, formProps.resetForm)}              type="button"            >              Reset            </button>          </Form>        );      }}    </Formik>  );}

If you really want to use onReset, I think the only way is to throw an error. The Formik source code seems to indicate resetForm() will be called no matter what your onReset() function returns.

const handleReset = () => {  if (!window.confirm('Reset?')) {    throw new Error('Cancel reset');  }};function Example() {  return (    <Formik initialValues={{ value: 1 }} onReset={handleReset}>      {formProps => {        return (          <Form>            <Field name="value" type="number" />            <button type="reset">              Reset            </button>          </Form>        );      }}    </Formik>  );}

I would still go with the first solution though personally.