question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to set initialValues when data is fetched asynchronously into multiple dropdown fields in redux form ?

See original GitHub issue

My application contains a redux form which has multiple dropdowns that fetch list of items asynchronously from remote api. Now what i want to do is set the first item from each of the list of items to be set to default, so i created multiple components in my form that does the fetching but how do i set the initial values ?

For e.g. i created UserSelectorInput component for fetching the list of users remotely.

class UserSelectorInput extends Component {

  constructor() {
    super()
    this.state = {
      loading: false,
      users: []
    }
  }

  componentDidMount() {
    // getAllUsers()  is an action creator that fetches the list of users from remote api 
    this.setState({ loading: true }, () => this.props.getAllUsers())
  }

  componentWillReceiveProps(nextProps) {
    const { allUsersList } = nextProps.users
    if (allUsersList) {
      const { users } = allUsersList
      if (users) {
        this.setState({ loading: false, users })

        // set the first user item as initial value
        var initialObject = {}
        initialObject[this.props.name] = users[0]._id
        this.props.initialize(initialObject)
      }
    }
  }

  render() {
    const { users, loading } = this.state
    return (
      <Field
        name={this.props.name}
        component={DropDownWithIcon}
        children={users}
        loading={loading}
        search={this.state.users.length > 5 && true}
        onChange={(e, value) => {
          if (this.props.reload) { this.props.reload(value) }
        } }
        label={this.props.label} />
    )
  }
}

const mapStateToProps = state => {
  return { users: state.users }
}

export default connect(mapStateToProps)(UserSelectorInput)

Similarly, there are other components in the form which fetch values but i cannot call this.props.initialize on them because it works only on the first component. So how do i set initial values for other components ?

What’s your environment?

Versions are as follows: “redux”: “^3.5.2”, “redux-form”: “^6.3.2”

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:11 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
sckohcommented, Jun 20, 2017

you need to set keepDirtyOnReinitialize to true to prevent initialValues being ovewritten

http://redux-form.com/6.8.0/docs/api/ReduxForm.md/

1reaction
jagjot2008commented, Jun 19, 2017

Thanks for the response but the problem is that i have multiple components (in the same redux form) that are fetching data from api.

Now i’m setting { initialValues: … } in mapStateToProps in each of these components but the initialValues is being set only for the first component. How do i set initialValues for each of these components ? For e.g.

class MyReduxForm extends Component {
    render() {
        const { handleSubmit, pristine, reset, submitting } = this.props
        return (
            <form ....>
                 // this is the first components which fetches the users list and sets the initialValue
                 // successfully
                 <UserSelectorInput
                    {...this.props}
                    name="user"
                    label="Owner" />
                 // this is the second component which fetches stages and here lies the problem
                 **// initialValues set here is not working even with** _enableReinitialize: true_
                 <DealStageSelectorInput
                    {...this.props}
                    name="stage"
                    label="Deal Stage" />
            </form>
       )
}

MyReduxForm = reduxForm({
  form: 'my_redux_form',
  validate,
  enableReinitialize: true
})(MyReduxForm);

const mapStateToProps = state => {
  return {
    initialValues: { 'user': localStorage.getItem('userId') },
    customizations: state.customizations,
    deals: state.deals
  }
}

export default connect(mapStateToProps)(MyReduxForm)

I can only set initialValue for any one of the component but i would like to initialize all of them.

I apologize for not being very clear in my earlier post.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Initializing From State - Redux Form
Pass a enableReinitialize prop or reduxForm() config parameter set to true to allow the form the reinitialize with new "pristine" values every time...
Read more >
Redux-Form initial values from - reactjs - Stack Overflow
To set the initialValues it is important to apply the reduxForm() decorator before the connect() decorator from redux. The fields will not ...
Read more >
React + Redux Form — Two ways to add initial values
1) Pass initialValues prop in form instance component ... We pass a prop called initialValues into the form instance component and the value...
Read more >
useForm | React Hook Form - Simple React forms validation
React hooks for form validation ... useForm is a custom hook for managing forms with ease. ... It supports both sync and async...
Read more >
Form - Ant Design
Including data collection, verification, and styles. When to use. When you need to create an instance or collect information. When you need to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found