Jeff Gao
Jeff Gao

Reputation: 153

How to reset form in formik using enableReinitialize?

I try to reset the form after the user clicks the cancel button.

I created a sample app to demonstrate the problem: https://codesandbox.io/s/dark-worker-ydzgs?fontsize=14

1) User clicks the Edit button to open a form to edit
2) User enters something in the field
3) User clicks the cancel button to close the form
4) user clicks the Edit button to open the form again

What I expect formik to do:
the form is reset

Actual result:
the form is not reset, it has the value the user enters in step 3

I could reset the form by calling the resetForm() method.

However, I am under the impression that enableReinitialize would reset the form

enableReinitialize?: boolean
Default is false. Control whether Formik should reset the form if the wrapped component props change (using deep equality).

Upvotes: 12

Views: 49436

Answers (1)

euvs
euvs

Reputation: 1645

Formik provides resetForm method for form reset.

Prior to calling this.props.onCancel you can call resetForm

For example


class MyForm extends Component {

    ....

    handleCancel = () => {
        this.props.resetForm()
        this.props.onCancel();
    }

    render() {

        return (
          <div>
            ....
            <div className="cancelButton">
              <button onClick={this.handleCancel}>Cancel</button>
            </div>
         </div>
    );
  }

}

const MyEnhancedForm = withFormik({
  initialValues: "",
  enableReinitialize: true,
  mapPropsToValues: props => ({ name: "" }),
  handleSubmit: (values, { setSubmitting }) => {},
  displayName: "BasicForm"
})(MyForm);


The enableReinitialize prop resets form only if initialValues is changed, but because your initial value is always the same (i.e. initialValues: ""), it never resets.

Upvotes: 17

Related Questions