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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With