Redux-form initialization with props.initialize()

Viewed 5786

We recently got some strange behaviors with redux-form (using 6.7.0). We were initializing data in componentDidMount()/componentWillMount() using code like:

componentWillMount() {
    this.props.initialize({type:'http',field:'A Value'});
    ...
}

But, only when we execute this initialization code, our submit function is not receiving the values being edited, but the initial ones. Also, the onChange() listener is no longer called when the values are edited. On the other hand, the state located in form/myform is properly updated, I can see the values being updated there. If I replace the call to initialize() by a dispatch() to the change action, for every single property:

this.props.dispatch(change("myform","type",'http'));
this.props.dispatch(change("myform","field",'A Value'));

Then it works!. It seems that initialize() replaces the whole object and breaks some internal references.

Use of initialValues also seems to work properly.

A lot of examples around are using props.initialize(), but we cannot get it to work. In what context should props.initialize() be called?

1 Answers

I had to populate my form using the existing data in my database on page load and update them when changes are made. The method below worked fine for me.

Make sure you set the values of enableReinitialize & keepDirtyOnReinitialize to true

export default reduxForm({
    validate,
    form : 'YourFormName',
    enableReinitialize: true,
    keepDirtyOnReinitialize : true
})(connect(mapStatetoProps, { actionReducers }(YourClassName))

And fire this.props.intialize() from ComponentDidMount(). Now use a state to make sure it only happens once and not every time any component gets updated.

componentDidMount(){
   this.props.dispatch(actionReducer(parameter)).then(()=>{
      this.props.initialize(this.props.data)
      this.setState({load:true})
   })
}
Related