Clear Redux-Form Fields after submitting
Asked Answered
Z

3

11

Hello and have a nice day, i'm new to react and redux and in my project we are not using statefull components, just stateless with containers. i have a redux form with four fields. When i submit my form i want the fields to get cleared. I see something about dispatch(reset('myForm'). My question is where i have to put it? In my container and passing it as prop to my component?

My container is like this:

const mapDispatchToProps = dispatch => (
  {
    submitOrdersTradesSearch: (formSearchOrdersTradesData) => {
      dispatch(searchOrdersTrades(formSearchOrdersTradesData));
    }
  }
);

const OrdersTradesSearchForm = reduxForm({
  form: 'ordersTradesSearchForm',
})(OrdersTradesSearch);

const OrdersTradesSearchContainer =
  connect(null, mapDispatchToProps)(OrdersTradesSearchForm);

export default OrdersTradesSearchContainer;
Zoography answered 2/3, 2017 at 9:49 Comment(0)
C
50

You can use onSubmitSuccess with reset.

import { reset, reduxForm } from 'redux-form';

const afterSubmit = (result, dispatch) =>
  dispatch(reset('ordersTradesSearchForm'));

const OrdersTradesSearchForm = reduxForm({
  form: 'ordersTradesSearchForm',
  onSubmitSuccess: afterSubmit,
})(OrdersTradesSearch);
Cresset answered 3/3, 2017 at 3:3 Comment(0)
W
4

Here is another Way of doing the same thing. - Redux provides a predefined method to handle submit called handleFormSubmit. You can basically do the same thing in that method as well, No need to use an extra method.

import React from "react";
import { reset, reduxForm } from "redux-form";

class Form extends React.Component {
  onSubmit = (formValues, dispatch) => {
    dispatch(reset("streamsForm")); // string here is the name of the form, check the export default reduxForm below.
  };

  render() {
    return (
      <form onSubmit={this.props.handleSubmit(this.onSubmit)}>
        // Your Form related Fields
      </form>
    );
  }
}

export default reduxForm({
  form: "streamsForm"
})(Form);
Worcestershire answered 24/1, 2019 at 9:9 Comment(0)
U
0

Just for the record, you can just call props.reset() on the component which has the reduxForm HOC. No extra line of code required.

Ursala answered 29/4, 2021 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.