Getting redux-form values in onChange event

10,140

With redux-form 6, you can get the values using the formValueSelector:

import { formValueSelector } from 'redux-form';

const selector = formValueSelector('myFormName');

connect(
  state => ({
      values: selector(state, 'fieldValue1', 'fieldValue2', 'fieldValue3');
  })
)(MyFormComponent);

Now you can compare the current values, and the previous values in componentWillReceiveProps:

componentWillReceiveProps(nextProps) {
    const nextValues = nextProps.values; 
    const values = this.props.values;
    // if at least one of the form values changed
    if(Object.keys(nextValues).some((key) => nextValues[key] !== values[key])) {
        console.log(nextProps.values); // do something with values
    }
}

Using redux-form up to version 6, you don't have to use the formValueSelector as redux-form add the values prop automatically to your decorated form.

Share:
10,140

Related videos on Youtube

Gregor Menih
Author by

Gregor Menih

Freelance web developer

Updated on June 04, 2022

Comments

  • Gregor Menih
    Gregor Menih almost 2 years

    What's the correct way of getting the values out of a form managed by redux-form after every form update? I need to dispatch an action every time the form changes, using the values entered into the form.

    My current solution gets the old values out, instead of the ones that were just updated.

      onFormChange(e) {
        const { fieldValue1, fieldValue2, fieldValue3 } = this.props.fields;
        console.log(fieldValue1.value, fieldValue2.value, fieldValue3.value);
      }
      render() {
        return (
          <form onChange={this.onFormChange}>
            // inputs here
          </form>
        );
      }
    

    My other solution is this, but I don't know how reliable it is:

      onFormChange(e) {
        console.log(e);
        setTimeout(() => {
          const { fieldValue1, fieldValue2, fieldValue3 } = this.props.fields;
          console.log(fieldValue1.value, fieldValue2.value, fieldValue3.value);
        }, 0);
      }
    
  • Dragos Rizescu
    Dragos Rizescu about 7 years
    The values props no longer exists.
  • vladimir khozeyev
    vladimir khozeyev over 5 years
    There is small mistake left. Please change if(Object.keys(nextValue) to if(Object.keys(nextValues)