Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discarding changes when using Formik with React

Tags:

reactjs

formik

I am using Formik form with React. Whenever the user submits (handleSubmit), I put an option whether or not to discard the change or keep the change.

In my render,

      <Formik
        initialValues={this.state.experiment}
        onSubmit={this.handleSubmit}
        component={formikProps => (
          <ExperimentForm {...formikProps} submitText="Save Changes" />
        )}
      />

handleSubmit()

  handleSubmit(formdata: any, actions: any) {
    const data = processFormData(formdata);

    let changes = this.detectChanges(this.state.experiment, data);

    this.setState({ tempFormData: data });
    // changed field exists
    if (changes.length !== 0) {

      this.setState({ 
        isDialogOpen: true,
        changedFields: changes,
      });

    } else {
      actions.setSubmitting(false);
      this.setState({
        message: 'Nothing Changed',
      });
    }
  }

keepChanges() and discardChanges()

  keepChanges () {

    const data = this.state.tempFormData
    makeMutation(UpdateExperimentQuery, {
      update: {
        id: this.props.match.params.id,
        data,
      },
    })
      .then(responseData => {
        console.log(responseData)
        this.setState({ isDialogOpen: false });

        this.props.history.push('/i/experiments');

      })
      .catch(err => {

        this.setState({
          message: 'Error Updating Experiment',
        });
        console.log(err);
      });

  }

  discardChanges () {
      this.setState({ isDialogOpen: false });
      this.componentWillMount();
  }

The keepChanges() successfully updates the data with the given field, but discardChanges just closes the dialog but does not reset the data to original value even though I try to call componentWillMount() which fetches and renders the original unchanged data in the DB.

How can I reset the fields when I choose to discard the changes?

Edit

  discardChanges () {
      this.formik.current.resetForm();
      this.setState({ isDialogOpen: false });
      this.componentWillMount();
  }

//I get an error when I do React.createRef();

class EditExperiment extends Component<EditExperimentProps, EditState> {
  constructor(props: EditExperimentProps) {
    super(props);
    this.formik = React.createRef();

    this.state = {
      experiment: null,
      message: null,
      changedFields: [],
      isDialogOpen: false,
      tempFormData: []
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.clearMessage = this.clearMessage.bind(this);
    this.detectChanges = this.detectChanges.bind(this);
    this.keepChanges = this.keepChanges.bind(this);
    this.discardChanges = this.discardChanges.bind(this);
  }

EDIT2

type EditExperimentProps = {
  history: RouterHistory,
  match: Match,
  experiments: ExperimentsState,
  refetch: () => void,
};
type EditState = {
  experiment: ?Experiment,
  message: ?string,
};

class EditExperiment extends Component<EditExperimentProps, EditState> {
  constructor(props: EditExperimentProps) {
    super(props);
    this.formik = React.createRef();

    this.state = {
      experiment: null,
      message: null,
      changedFields: [],
      isDialogOpen: false,
      tempFormData: []
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.clearMessage = this.clearMessage.bind(this);
    this.detectChanges = this.detectChanges.bind(this);
    this.keepChanges = this.keepChanges.bind(this);
    this.discardChanges = this.discardChanges.bind(this);
  }
like image 828
Dawn17 Avatar asked May 30 '18 16:05

Dawn17


2 Answers

To reset the Formik you need to call resetForm - see an example here.

  handleSubmit(formdata: any, actions: any) {
    ...

    // changed field exists
    if (changes.length !== 0) {
      ...
    } else {
      actions.setSubmitting(false);
      actions.resetForm();
    }
  }

EDIT:

There is another way to get "actions" and call them wherever in component by using react refs:

constructor(props) {
  super(props);
  this.formik = React.createRef();
}

//somewhere in render

<Formik
  ref={this.formik}
  initialValues={this.state.experiment}
  onSubmit={this.handleSubmit}
  component={formikProps => (
    <ExperimentForm {...formikProps} submitText="Save Changes" />
  )}
/>

// now somewhere else in the same component ...
componentDidUpdate(prevProps) {
  if(somethingHappend) {
    if(this.formik.current) {
      this.formik.current.resetForm();
    }
  }
}
like image 176
Tomasz Mularczyk Avatar answered Nov 07 '22 12:11

Tomasz Mularczyk


You need to include the initial state when you want to use resetForm. Example:

    this.formik.current.resetForm(this.initialState.experiment);

This means you need to save the initialState too:

constructor(props) {
    super(props);
    this.initialState = this.state;
}
like image 39
Diego Berolatti Avatar answered Nov 07 '22 12:11

Diego Berolatti