How to clear some fields in form - Redux-Form
Asked Answered
T

10

24

I'm working on a page which has many input validations and logical bindings on it and every sprint iteration the page size increasing. So that, I have to find a beautiful and scalable solution.

Imagine, when user select a value from dropdown as 'A', some fields must be disabled, some fields must be cleared and some fields initilized with default values. I can change one related field (doesn't have validation rule like regexp or lenght constrait) value with some little code like

  this.props.dispatch(change('xForm','xField','xValue' ))

My problem is that when I need to clear multiple fields,

It always blocked by my validation method and clear operation is failed ( Note : I supposed to be like that but not like that)

.

I tried some strategies as below but y,z,w fields have some text and it triggered validation rule and hanled errors. So that, inputs have still old values, not cleared ones.

    //Clear    
    this.props.dispatch(change('xForm','yField','' ))
    this.props.dispatch(change('xForm','zField','' ))
    this.props.dispatch(change('xForm','wField','' ))

What are the best practises for clear inputs or assign some values to inputs in redux-form for pages which have highly dependent inputs.

I have been researching for 2 days but I couldn't find any optimal solution. (redux normalizer, redux form utils etc.)

Thanks.

Townsville answered 12/5, 2016 at 14:25 Comment(1)
are you using immutable.js?Strudel
S
5

Wow, that's some complicated logic. The absolute ideal way would be to use the plugin() API to change values in the reducer when your other field values change. It's a complicated API, because you have total control to mess things up in the reducer, but you have a complicated requirement.

However, dispatching three change() actions like you said you are doing should also work fine. You might want/need to untouch() the fields as well if they have Required validation messages that you don't want to show yet.

It always blocked by my validation method and clear operation is failed.

Can you elaborate on what that means, show a stack trace or console error output?

Sesame answered 16/5, 2016 at 15:7 Comment(4)
Hi Erik, I solved the problem with some tricks. Not ideal solution but works fine. I will improve it with your suggestions.Townsville
And I'm going to explain how I solved it. And note that untouch() saved me.Townsville
This is a little older... currently I am on 6.5.0 but I am struggling with the untouch dispatching. Is there an example of how to dispatch an untouch() action ? Even though I "change" and then "untouch" fields they are still submitted..Wrigley
@Townsville I met the same problem, and try the methods below, none of them work, could you tell me how did you achieve that?Genevagenevan
W
16

This worked for me:

resetAdvancedFilters(){
        const fields = ['my','fields','do','reset','properly']
        for (var i = 0; i < fields.length; i++) {
            this.props.dispatch(change('formName',fields[i],null))
            this.props.dispatch(untouch('formName',fields[i]))
        }
    }
Wrigley answered 15/3, 2017 at 2:47 Comment(0)
M
12

Using the below, it clears the respective multiple fields and also clears the errors if any for those respective fields.

Common function to reset multiple fields.

import {change, untouch} from 'redux-form';

//reset the respective fields's value with the error if any
resetFields = (formName, fieldsObj) => {
      Object.keys(fieldsObj).forEach(fieldKey => {

          //reset the field's value
          this.props.dispatch(change(formName, fieldKey, fieldsObj[fieldKey]));

          //reset the field's error
          this.props.dispatch(untouch(formName, fieldKey));

      });
}

Use the above common function as,

this.resetFields('userDetails', {
    firstName: '',
    lastName: '',
    dateOfBirth: ''
});
Melamine answered 25/9, 2017 at 7:29 Comment(1)
I did it exacty like that.Townsville
S
5

Wow, that's some complicated logic. The absolute ideal way would be to use the plugin() API to change values in the reducer when your other field values change. It's a complicated API, because you have total control to mess things up in the reducer, but you have a complicated requirement.

However, dispatching three change() actions like you said you are doing should also work fine. You might want/need to untouch() the fields as well if they have Required validation messages that you don't want to show yet.

It always blocked by my validation method and clear operation is failed.

Can you elaborate on what that means, show a stack trace or console error output?

Sesame answered 16/5, 2016 at 15:7 Comment(4)
Hi Erik, I solved the problem with some tricks. Not ideal solution but works fine. I will improve it with your suggestions.Townsville
And I'm going to explain how I solved it. And note that untouch() saved me.Townsville
This is a little older... currently I am on 6.5.0 but I am struggling with the untouch dispatching. Is there an example of how to dispatch an untouch() action ? Even though I "change" and then "untouch" fields they are still submitted..Wrigley
@Townsville I met the same problem, and try the methods below, none of them work, could you tell me how did you achieve that?Genevagenevan
S
1

there.

Let's look at http://redux-form.com/6.0.0-alpha.4/docs/faq/HowToClear.md/

For whole form we can use 4 methods:

A) You can use the plugin() API to teach the redux-form reducer to respond to the action dispatched when your submission succeeds.

B) Simply unmount your form component

C) You can call this.props.resetForm() from inside your form after your submission succeeds.

D) You can dispatch reset() from any connected component

Stellular answered 27/5, 2017 at 20:35 Comment(0)
L
1

Try to use the dispatch function in meta object with following payload:

meta.dispatch({
  type: '@@redux-form/CHANGE',
  payload: null,
  meta: { ...meta, field: name },
})

That should do the trick for any field you want.

Laylalayman answered 7/12, 2017 at 10:59 Comment(2)
It works but why does it work? Can you point me to any references or documentation?Deliquesce
It works because that you dispatch the action for redux-form directly. If you use redux-logger as middleware, you will see what redux-form will dispatch under the hood. And so you can dispatch by yourself.Laylalayman
M
1

I found a better way for this,

We can use initialize action creator of RF.

let resetFields = {
    firstName: '',
    lastName: '',
    dateOfBirth: ''
}

this.props.initialize(resetFields, true); //keepDirty = true;

If the keepDirty parameter is true, the values of currently dirty fields will be retained to avoid overwriting user edits.

Melamine answered 17/2, 2018 at 14:47 Comment(0)
P
1

You can use the clearFields prop or action creator to clear multiple fields.

For example, in this simple form, I use the clearFields prop to clear the firstName and lastName fields.

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

const SimpleForm = (props) => {
  const { clearFields } = props;

  const clearName = (e) => {
    e.preventDefault();
    clearFields(false, false, ...["firstName", "lastName"]);
  };

  return (
    <form>
      <div>
        <label>First Name</label>
        <Field name="firstName" component="input" type="text" />
      </div>
      <div>
        <label>Last Name</label>
        <Field name="lastName" component="input" type="text" />
      </div>
      <div>
        <label>Occupation</label>
        <Field name="occupation" component="input" type="text" />
      </div>
      <button onClick={clearName}>Clear Name</button>
    </form>
  );
};

export default reduxForm({
  form: "simple"
})(SimpleForm);
Plummy answered 17/2, 2023 at 14:47 Comment(0)
J
0

clear multiple fields

import {change} from 'redux-form';

const fields = {name: '', address: ''};
const formName = 'myform';

const resetForm = (fields, form) => {
    Object.keys(fields).forEach(field => dispatch(change(form, field, fields[field])));
}

resetForm(fields,formName);
Juice answered 27/7, 2017 at 4:5 Comment(2)
I get this Uncaught ReferenceError: dispatch is not definedMosquito
use this.props.dispatch or const dispatch = useDispatch()Bratwurst
G
0

If we are talking about entering fields into a form, and then navigating away before submitting, this is the best solution. Place this in your componentDidMount() with the fields you want cleared.

 this.props.initialize({
    firstName: null,
    lastName: null,
    bankRoutingNum: null,
    newBankType: null
  });
Guardi answered 2/10, 2019 at 23:38 Comment(1)
How can I do it in a functional component?Mosquito
M
0

For a functional component, you can you change function of RF. Pass change as props to your component and use it like change(Field_name, value)

For example:

import { reduxForm } from "redux-form";
const Screen = ({
    handleSubmit,
    change
}) => {
onChange = () => {
    change(Field_name, value)
}
return (
// Your code
)}
Mosquito answered 2/6, 2022 at 10:59 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.