RamSom
RamSom

Reputation: 29

Use initialValues on component utilizing async data population

I am trying to pre-populate Personal Info however I am running into an async issue. Any help will be appreciated.

looked at : https://medium.com/@1sherlynn/react-redux-form-two-ways-to-add-initial-values-ab48daa0a32e and https://redux-form.com/6.0.0-alpha.4/examples/initializefromstate/

class AccountOverview extends Component {

  constructor() {
    super();
    this.state = { data: [] };
  }

  async componentDidMount() {
    const data = { fullname: "fullname", username: "username" }

    this.setState({ data })

  }

  render() {
     console.log(this.state.data)

     <PersonalInfo
     initialValues={this.state.data} />

     ....

I expect the form to be populated by the data state. I logged with he the following result

[]
{ fullname: "fullname", username: "username" }

i feel the component does not reload after the async call is completed.

PersonalInfo.js:

const PersonalInfo = props => {

const { username, fullname, handleOnChange, validationErrors } = props;

return (
    <div>
    <h1> Personal Information</h1>
    <br />
    <Field
        type="text"
        name="fullname"
        icon=""
        label="Fullname"
        value={fullname}
        component={FormField}
        onChange={handleOnChange}
    />
    <Field
        type="text"
        name="username"
        icon=""
        label="Username"
        value={username}
        component={FormField}
        onChange={handleOnChange}
    />
    </div>
)

}

function mapStateToProps(state) {

return {
    state
   };

}

export default reduxForm({form: "AccountOverview"})(connect(mapStateToProps)(PersonalInfo))

Upvotes: 2

Views: 32

Answers (1)

ravibagul91
ravibagul91

Reputation: 20755

From the docs, you have missed important step.

Add initialValuesprop in mapStateToProps and you can retrieve initialValues from the redux store

So your mapStateToProps should be,

const mapStateToProps = (state, props) => ({
  initialValues: state, // retrieve data from redux store 
})

To pass the initialValues props into the redux form, we use the connect function

Add enableReinitialize : true When set to true, the form will reinitialize every time the initialValues prop changes

This,

export default reduxForm({form: "AccountOverview"})(connect(mapStateToProps)(PersonalInfo))

Should be,

export default connect(
  mapStateToProps
)(reduxForm({
   form: 'AccountOverview', // a unique identifier for this form
  enableReinitialize: true
})(PersonalInfo))

Upvotes: 1

Related Questions