How to reset form after confirmation in Formik

React JS Faysal Shuvo

Problem:

You are using Formik to reset the form in your react application. But It is not working. In this article, I will tell you formik - how to reset the form after confirmation.

const resetHandler = (values, props) => {
    return window.confirm('Reset?'); // still resets after you Cancel :(
};
return (
  <Formik onReset={resetHandler}>
    {(props) => { 
      return (
        <Form>
          ...
          <button type='reset'>Reset</button>
        </Form>
      )}}
  </Formik>
);


Solution 1:

You can write your reset function without a button with reset type. This is how you do it:

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

And if you want to use onReset the only way of doing it is to throw an error. To throw the error you can follow this code:

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


Solution 2:

The other way of doing it is to use resetForm in onSubmit.

This is what resetForm do:

1. It reset the form.

2. It will clear any errors you have.

3. It sets isSubmitting to false and isValidating to false.

So basically reset will either reset the entire form state or part of the form state.

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

Thank you for reading this article. If you have any problem comment down below