Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting redux-form values in onChange event

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);
  }
like image 718
Gregor Menih Avatar asked Aug 03 '16 16:08

Gregor Menih


1 Answers

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.

like image 146
Ori Drori Avatar answered Oct 26 '22 20:10

Ori Drori