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

108
Visualizações
Cleanup a function with parameters inside a loop of event listener (reactjs)

I don't really know what is going on, but I think that the removeEventListener is not working properly. Here is my code, my app is crashing everytime I click more than 5 times on any of the buttons and I can't find a solution anywhere.

const doTri = (e) => {
    if(e.id === "active"){
      setOrder(!order);
    }
    else {
      document.getElementById("active")?.removeAttribute("id");
      e.setAttribute('id', 'active');
      setTri(e.classList[1]);
      setOrder(true)
    }
  }

useEffect(() => {
    Array.from(document.getElementsByClassName("headerBtn")).forEach((e)=>{
      e.addEventListener('click', ()=>{doTri(e)})
    })
  
    return () => {
      Array.from(document.getElementsByClassName("headerBtn")).forEach((e)=>{
        e.removeEventListener('click',()=>{doTri(e)})
      })
    }
  }, [tri,order])
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

as I said the removeEventListener function wasn't working so I did some changes in order to not pass any params to the do tri functions, that is what I did and it worked.

const doTri = (e) => {
    if(e.currentTarget.id === "active"){
      setOrder(!order);
    }
    else {
      document.getElementById("active")?.removeAttribute("id");
      e.currentTarget.setAttribute('id', 'active');
      setTri(e.currentTarget.classList[1]);
      setOrder(true)
    }
  }

useEffect(() => {
    Array.from(document.getElementsByClassName("headerBtn")).forEach((e)=>{
      e.addEventListener('click', doTri)
    })
  
    return () => {
      Array.from(document.getElementsByClassName("headerBtn")).forEach((e)=>{
        e.removeEventListener('click', doTri)
      })
    }
  }, [tri,order])
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