0
votes

In my component, I have the following:

componentWillReceiveProps(nextProps) {
  if (nextProps.industries.items.length > 0) {
    this.setState({
      industry_item_id : nextProps.industries.items.find(el => el.title === "XXXX").id
    });
  }

I then want to use this value in my Redux Form's initialValue like so:

myForm = reduxForm({
  form: 'myForm',
  initialValues: {
    industry_id: this.state.industry_item_id
  },  
})(myForm);

...
export default connect(mapStateToProps, mapDispatchToProps)(myForm);

How can I use this.state within the initialValues? Also, this.state.industry_item_id is not defined on ComponentMount, will this work when the value of this.state.industry_item_id is set with componentWillReceiveProps(nextProps)?

I'm using "redux-form": "^6.6.3".

4

4 Answers

2
votes

You can use initialize action to set initial values of your form anytime (i.e. when all the values you want to set are defined).

import { initialize } from 'redux-form';

then somewhere in your component use:

this.props.dispatch(initialize(<name of your form>, <values you want to set>));
2
votes

In your mapStateToProps function in your container add this:

const mapStateToProps = (state, ownProps) => (
    initialValues: fromJS({
           industry_id: ownProps.industry_item_id
        })
)
0
votes

This is a good reference to the above problem: http://redux-form.com/6.0.0-alpha.4/examples/initializeFromState/

componentWillReceiveProps(nextProps) {
    if (nextProps.industries.items.length > 0) {
       this.setState({
         industry_item_id : nextProps.industries.items.find(el => el.title === "XXXX").id
       }, () => {
        // callback of setState, because setState is async.
        // dispatch the action via this function.
        this.props.load(this.state.industry_item_id);
       });
    }
 }


 myForm = reduxForm({
     form: 'myForm',
     initialValues: {
         // Connect the value through industry reducer.
         industry_id: state.industryReducer.id
     },  
 })(myForm);

 ...
 export default connect(mapStateToProps, mapDispatchToProps)(myForm);

The actions and reducers:

const LOAD = 'redux-form-examples/account/LOAD'

const reducer = (state = {}, action) => {
  switch (action.type) {
    case LOAD:
      return {
        data: action.data
      }
    default:
      return state
  }
}

/**
 * Simulates data loaded into this reducer from somewhere
 */
export const load = data => ({ type: LOAD, data })

export default reducer
0
votes

Using this in my reduxForm component worked for me:

componentWillMount () { this.props.initialize({ name: 'value' }) }

Where 'name' corresponds to the name of the form field. Hope it is of help.