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)
}
CodePudding user response:
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