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.
Related videos on Youtube
Comments
-
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 about 7 yearsThe
values
props no longer exists. -
vladimir khozeyev over 5 yearsThere is small mistake left. Please change
if(Object.keys(nextValue)
toif(Object.keys(nextValues)