user3574492
user3574492

Reputation: 6435

React life cycle method for making API call when component is re-rendered

I have a component called <Header> where I have a log-in form that makes an API call to log a user in.

I have a function in my header component that makes some API calls to fetch some data and update the menu items in the header once successfully logged in:

componentDidMount() {
        const { auth, actions, children } = this.props;;
        if (auth.isLoggedIn) {
            actions.getAssessmentRequest();
            actions.getFirstSubsectionRequest();
        }
    }

The problem I am having is that the very first time the user logs in the above componentDidMount function does not trigger because the header component was already mounted the first time the page was loaded.

I have tried to use componentDidUpdate and componentWillReceiveProps but they get triggered multiple times and I get request timeout errors.

Any ideas which lifecycle method I could use to achieve this?

Upvotes: 0

Views: 1288

Answers (2)

Apurva jain
Apurva jain

Reputation: 1590

I can't tell you why it is called multiple times, but I can tell you that it should not matter. The problem is that you're not comparing the props for what has changed. If you do this, the code will behave the way you want:

componentWillReceiveProps(newProps) {
  const { auth, actions, children } = newProps;
  if (auth.isLoggedIn !== this.props.auth.isLogin) {
    actions.getAssessmentRequest();
    actions.getFirstSubsectionRequest();
  }
}

See also the official ReactJS documentation, which states: https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops

Hope this helps.

Upvotes: 0

Chase DeAnda
Chase DeAnda

Reputation: 16441

Yes you are on the right path, you should use the componentWillReceiveProps lifecycle method. The trick to prevent infinite loops and constantly making requests, you have to perform a check to test whether the props you care about actually changed or not:

componentDidMount() {
    this.fetchData(this.props);
}

componentWillReceiveProps(nextProps) {
    if(nextProps.auth.isLoggedIn !== this.props.auth.isLoggedIn) {
        this.fetchData(nextProps);
    }
}

fetchData(props) {
    const { auth, actions, children } = props;
    if (auth.isLoggedIn) {
        actions.getAssessmentRequest();
        actions.getFirstSubsectionRequest();
    }
}

Upvotes: 3

Related Questions