Redux Form - initialValues not updating with state

爱⌒轻易说出口 提交于 2019-12-02 22:40:17

I was facing the same problem after update to redux-form v6.0.0-rc.4.

I solved setting enableReinitialize to true

UsersShowForm = reduxForm({
  form: 'UsersShowForm',
  enableReinitialize: true
})(UsersShowForm)

To pre-fill a redux-form form with data from a resource, you would use the initialValues prop which is read automatically when decorating the component/container with the reduxForm connector. It's important that the keys in the initialValues match the name on the form fields.

Note: It is necessary to first apply the reduxForm() decorator, and then the connect() from redux. It will not work the other way around.

Using redux-form 7.2.3:

const connectedReduxForm = reduxForm({
 form: 'someUniqueFormId',
  // resets the values every time the state changes
  // use only if you need to re-populate when the state changes
  //enableReinitialize : true 
})(UserForm);

export default connect(
  (state) => { 
    // map state to props
    // important: initialValues prop will be read by redux-form
    // the keys must match the `name` property of the each form field
    initialValues: state.user 
  },
  { fetchUser } // map dispatch to props
)(connectedReduxForm) 

From the official documentation:

Values provided to the initialValues prop or reduxForm() config parameter will be loaded into the form state and treated thereafter as "pristine". They will also be the values that will be returned to when reset() is dispatched. In addition to saving the "pristine" values, initializing your form will overwrite any existing values.

Find more information and a complete example in the official documentation

In my case I have Redux Form, 2 Route with small url param changes. When Switching between component Props were not getting updated. It kept showing blank form.

Example: baseurl/:id/personal -> baseurl/:id/employment

After debugging I found that mapStateToProps is not firing sometime where Initial values are set.

<React.Fragment>
  <Route
    exact={true}
    path="/path1"
    component={PersonalDetails}
    key="personal"
  />
  <Route
    exact={true}
    path="/path1/employment"
    component={Employment}
    key="employment"
  />
</React.Fragment>

setting destroyOnUnmount to false mapStateToProps fixed my issue, where its default is true.

    enableReinitialize: true,
    destroyOnUnmount: false

Example using above :

UsersShowForm = reduxForm({
  form: 'UsersShowForm',
  enableReinitialize: true,
  destroyOnUnmount: false
})(UsersShowForm)

Read more : destroyOnMount

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!