Home > OS >  Adding ifcondition in componentdidupdate in react but then also infinite loop
Adding ifcondition in componentdidupdate in react but then also infinite loop

Time:04-15

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,
  });
}

}

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

CodePudding user response:

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 ) {
    ...
  }
}
  • Related