reactjsreact-reduxredux-formreact-redux-form

Redux-Form, how to use formValueSelector with dynamic Field names?


I'm using redux form and trying to create a Field component like so:

<Rating
  stop={10}
  initialRate={selector(this.props.state, 'age')}
  onRate={(rate) => this.onRateChange(rate)}
  onChange={(value) => { this.changeRate("name", value) } }
/>
<span className="label label-default" id="label-onrate">{this.state.label}</span>

<Field
  name="age"
  type="number"
  component={renderField2}
/>

RateForm = reduxForm({
  form: 'rateForm'
})(RateForm);

const selector = formValueSelector('rateForm');

const mapStateToProps = state => {
  return {
  };
};

export default connect(mapStateToProps)(RateForm);

The problem I'm having is initialRate is not working... the following is not returning a value:

selector(this.props.state, 'age')

Because the field name will be dynamic, I need to avoid:

defining the specific field name in mapStateToProps.

What am I doing wrong with redux-form formValueSelector to not provide initialRate with a value?


Solution

  • You can do something like this:

    import { getFormValues } from 'redux-form/immutable'
    

    getFormValues will return the values saved corresponding to the form name provided.

    const mapStateToProps = state => {
      const formState = getFormValues('rateForm')(state)
      console.log('formState...', formState)
      return formState 
    }
    

    This is working fine for me. I am getting values of all the Field component rendered particular to this form i.e rateForm in your case. For more details, you can go here.