Formik - How to reset form after confirmation

Aximili picture Aximili · Apr 9, 2019 · Viewed 38.7k times · Source

In Formik, how to make the Reset button reset the form only after confirmation?

My code below still resets the form even when you click Cancel.

var handleReset = (values, formProps) => {
    return window.confirm('Reset?'); // still resets after you Cancel :(
};

return (
  <Formik onReset={handleReset}>
    {(formProps) => { 
      return (
        <Form>
          ...
          <button type='reset'>Reset</button>
        </Form>
      )}}
  </Formik>
);

Answer

patelarpan picture patelarpan · Apr 23, 2019

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.