Search code examples
reactjsreduxredux-form

Passing initial values in redux form on page load


I'm passing initial value to redux form. I'm getting the data while componentWillMount.

When the page is loaded, I'm getting error as, Cannot read property 'id' of undefined. If I refresh the page, data will be there.

Can anyone please help me.

This is my code.

componentWillMount() {
    this.props.actions.getService(this.props.params.Id);
}

 const mapStateToProps = (state) => {
     return {
         initialValues: {
             user_id:state.userInfo.data.user.id,
        }
    }
}

Thank you.


Solution

  • Another way you can do this is by using this.props.initialize, which Redux Form adds for you. You could also use lodash's .get method to prevent having to add extensive checks like this: if (nextState.userInfo && nextState.userInfo.data && nextState.userInfo.data.user && nextState.userInfo.data.user.id && nextState.userInfo.data.user.id !== this.state.userInfo.data.user.id)

    Something like this should work:

    componentWillReceiveProps = (nextProps) => {
        if (_.get(nextProps, 'userInfo.data.user.id') !== _.get(this.props, 'userInfo.data.user.id')) {
            this.props.initialize({ user_id: nextProps.userInfo.data.user.id });
        }
    }
    
    mapStateToProps = (state) => {
        return {
            userInfo: state.userInfo,
        };
    }