Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding ifcondition in componentdidupdate in react but then also infinite loop

I have a link tag I am sending it to same component but with different parameter. For that I am using componentdidupdate .If I would have used anchor tag then it was not required. I added a if condition in componentdidupdate and then a url request and setting the state but getting infinite loop. Infinite request going to server
Code of link

Link to={`/tutorials/${id}/${courseid}`}>{title}</Link>

In componentdidupdate

async componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.params.id !== prevState.id ) {
  const { id } = this.props.params;
  const { courseid } = this.props.params;
  let url = `https://localhost:7058/Dashboard/api/Tutorial?ID=${courseid}`;
  this.setState({
    loading: true,
  });
  let data = await fetch(url);
  let parsedData = await data.json();
  this.setState({
    lectures: parsedData,
    courseid: courseid,
    id: id,
    loading: false,
  });
  //now api request for description
  let durl = `https://localhost:7058/Dashboard/api/Tutorial/GetTutorial?ID=${courseid}&TutorialID=${id}`;
  this.setState({
    loading: true,
  });
  let ddata = await fetch(durl);
  let dparsedData = await ddata.json();
  // console.log(dparsedData);
  this.setState({
    desc: dparsedData,
    loading: false,
  });
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default (props) => <Tutorial {...props} params={useParams()} />;

I am using react 18 and react router dom 6. Provide solution for this version , please don’t suggest either to degrade version or change it to function based component

>Solution :

I think the condition is malformed, you likely want to compare against prevProps.params.id, or maybe this.state.id since it would have been updated on a previous render cycle.

Example:

async componentDidUpdate(prevProps, prevState, snapshot) {
  if (this.props.params.id !== prevProps.params.id ) {
    ...
  }
}

or

async componentDidUpdate(prevProps, prevState, snapshot) {
  if (this.props.params.id !== this.state.id ) {
    ...
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading