farooq
farooq

Reputation: 1673

ComponentDidUpdate() keeps calling the API always even after having condition

So I have a component which will be called in parent component when a button clicked. I have added a condition to run ComponentDidUpdate run only once. But still it calls the API multiple times. Here is my code:

componentDidUpdate(prevProps) {
  var seqNum = this.props.seqNum;

  // Condition to control multiple requests
  if (prevProps.seqNum !== seqNum) {
   this.getCheckList();
  }
}

getCheckList() {
  var seqNum = this.props.seqNum;
  var vehicleId = this.props.vehicleId;

  // Get EventDetails
  var urlLink = "getEvent?vehicleId=" + vehicleId + "&seqNum=" + seqNum;
  axios.get(urlLink)
    .then(res => {
      this.setState({ eventData: res.data })
      console.log(res.data + "This fil")
  })
}

Why is this happening ? Any ideas? Or if you need any additional info, just ask me. I will update the code here.

Upvotes: 0

Views: 166

Answers (1)

Babak Yaghoobi
Babak Yaghoobi

Reputation: 1985

in you state initializing in your component constructor set eventData: null

then try this :

componentDidUpdate(prevProps, prevState) {
  var seqNum = this.props.seqNum;
  var eventData= this.state.eventData;
  //Condition to control multiple requests

  // or you can add something to check state for fetching more than once !
  if(prevProps.seqNum !== seqNum && (!eventData || prevState.eventData != eventData ) {
   this.getCheckList();
  }
}

getCheckList() {
 var seqNum = this.props.seqNum;
 var vehicleId = this.props.vehicleId;
 //Get EventDetails
 var urlLink = "getEvent?vehicleId="+vehicleId+"&seqNum="+seqNum;
 axios.get(urlLink)
   .then(res => {
     this.setState({eventData: res.data})
     console.log(res.data+ "This fil")
   })
}

or maybe just this enough :

if(prevProps.seqNum !== seqNum && !eventData  )

Upvotes: 1

Related Questions