Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
reactjs Avoid Infinite loop using the useState and useEffect

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)
  }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda