2

How to avoid infinite loop? I mean in the first click the StudentSubject must be undefined, and in the second click it will get the data, in my current code the result are infinite loop, it keeps looping the console.log(getStudentId, getRelevance) how to avoid that?

  const [getStudentId, setStudentId]= useState();
  const [getRelevance, setRelevance]= useState();

  useEffect(() => {
    student();
  }, []);
  
  const onClickGrade = (studentId, relevance) => {

   .....
    console.log(getStudentId, getRelevance) //undefined
    if(StudentSubject === undefined){
        onClickGrade(studentId, relevance) //infinite loop
    }
   ....
  }

  const student = () => {
    .....
    view.on('click', onClickMap);
    .....
  }

  const onClickStudent = (event)=>{
      const studentId = student.getAttribute('id');
      const relevance = student.getAttribute('relevance');
      setStudentId(studentId)
      setRelevance(relevance)
      onClickGrade(studentId, relevance)
  }
  • Did you use console.log() for studentId and relevance at the onClickStudent? On the other hand, since React uses a Virtual Dom, I do not like the use of getAttribute. Can you, for student, use another react component? – Jose Cabrera Zuniga Feb 21 '22 at 18:21
  • You might also like to check: https://stackoverflow.com/questions/20377837/how-to-access-custom-attributes-from-event-object-in-react – Jose Cabrera Zuniga Feb 21 '22 at 18:25
  • Finally, since I started with React, for text boxes, I do prefer to create react components and trash "html" stuff. My html view is practically empty and just calling the js file that is the compilation of my React code. – Jose Cabrera Zuniga Feb 21 '22 at 18:31

1 Answers1

0

You are recursively calling onClickGrade

const onClickGrade = (studentId, relevance) => {

   .....
        onClickGrade(studentId, relevance) ## Infinite loop in a recursive call
   ....
  }

It depends on what you wants to achieve but you certainly need to change your logic or at least add a condition to prevent an infinite loop in recursion! Your studentSubject sounds to stay always undefined. You might need to save prevStudentSubject and compare that with the current subject.

if (studnetSubject === prevStendentSubject) return