Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset form in formik using enableReinitialize?

Tags:

reactjs

formik

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).
like image 777
Jeff Gao Avatar asked Nov 09 '19 01:11

Jeff Gao


People also ask

How do you use handleChange in Formik?

Now we must write the handleChange method to update the state with user inputs: handleChange = ({ target }) => { const { formValues } = this. state; formValues[target.name] = target. value; this.

What is dirty Formik?

Returns true if values are not deeply equal from initial values, false otherwise. dirty is a readonly computed property and should not be mutated directly.


1 Answers

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.

like image 156
euvs Avatar answered Oct 19 '22 12:10

euvs