1
votes

I have a component which is dependent on redux store. My redux store looks like this something

{
  user: {
    auth: true,
    id: '5a603c58288fc745f8cada9e',
    first_name: 'john',
    email: '[email protected]',
    company_id: '5a66d8b92cd8e931680778dc',
    company_name: 'My Company',
  }
}

So basically when i refresh the page, store goes away and it takes sometime to fetch data and set it into store as above

I have a component which requires company_id to fetch data about that company

 componentDidMount(props) {
      console.log("idddddddd", this.props.company_id)
    // this.props.getCompanyData(this.props.company_id);
  }

using react-redux i am getting the company_id

CompanySetupPage.propTypes = {
  getCompanyData : PropTypes.func.isRequired,
  company_id : PropTypes.string.isRequired
}

function mapStateToProps(state) {
  return {
    company_id : state.user.company_id
  }
}

export default connect(mapStateToProps, {getCompanyData})(CompanySetupPage);

this component, componentDidMount is being fired before store receives company_id data. So what i want is i want componentDidMount to be called after this component gets company_id from redux store.

2
You don't have to change the order in which the component lifecycle functions are called, what you need is the componentWillReceiveProps lifecycle hookShubham Khatri
how would i use this?waq
Glad it helped,Shubham Khatri
consider upvoting questions and answers on SO that helpShubham Khatri

2 Answers

0
votes

what i want is i want componentDidMount to be called after this component gets company_id from redux store.

It is better to not modify when component life cycle method will be called. See this refs to read more about component lifecycle method.

componentDidMount is triggered only once after component is mounted. company_id may or mayn't available

Better function to invoke api call in your case will be componentWillReceiveProps.

componentWillReceiveProps() is invoked before a mounted component receives new props. While mounting it is not invoked.

  componentWillReceiveProps (nextProps) {
     if (this.props.company_id !== nextProps.company_id) {
        this.props.getCompanyData(this.props.company_id);
     }
    }
0
votes

Instead of using componentDidMount life cycle use componentWillReceiveProps life cycle method, like below

componentWillReceiveProps (nextProps) {
 if (this.props.company_id !== nextProps.company_id) {
    this.props.getCompanyData(this.props.company_id);
 }
}

For reference have a look at the documentation for this life cycle method. Docs For componentWillReceiveProps