Discarding changes when using Formik with React

Deadly 提交于 2020-12-05 05:43:08

问题


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);
  }

回答1:


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();
    }
  }
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/50609944/discarding-changes-when-using-formik-with-react

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!