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

178
Visualizações
Why do I get two console logs while its should be just one ? react js

I have a simple section in react which contains two buttons logo and banner, on click I am opening a simple modal from web component, now I want when user click cancel to show me something on the console.

Problem: When I click eg Logo button which opens the modal and I click cancel I get the console log I want, and then I click the banner button and open the modal and I click cancel, instead of giving just logs related to the banner button I get both of logs.

my code Live demo : live demo

import * as element from "./custom-element";

const Images = () => {
  const [imgName, setImgName] = useState();
  const [logo, setLogo] = useState();
  const [banner, setBanner] = useState();
  const elementRef = useRef(null);

  const handleUseImage = () => {
    switch (imgName) {
      case "logo":
        console.log("logo name", imgName);
        break;
      case "banner":
        console.log("banner name", imgName);
        break;
      default:
    }
  };

  useEffect(() => {
    if (imgName) {
      elementRef.current.addEventListener("cancel", function (e) {
        handleUseImage(e);
      });
    }
  }, [imgName]);

  const handleLogo = () => {
    setImgName("logo");
    openModal();
  };
  const handleBanner = () => {
    setImgName("banner");
    openModal();
  };
  const openModal = () => {
    elementRef.current.visible = true;
  };
  return (
    <div className="App">
      <custom-element ref={elementRef}></custom-element>
      <button onClick={handleLogo}>Logo </button>
      <button onClick={handleBanner}>Banner </button>
      <span>Logo url: {logo} </span>
      <span>banner url: {banner} </span>
    </div>
  );
};

export default Images;

[enter image description here][2

Why do I get both logs?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I could be wrong, but I'm pretty sure the issue is that you never remove the event listener, so when you call setImgName it will rerender, and now you'll have two event listeners, one which is "out of scope" (for lack of a better term - it doesn't have the the "current" state values, as it was from a previous render). I would try

useEffect(() => {
  if (imgName) {
    elementRef.current.addEventListener("cancel", handleUseImage);
    return () => {
        elementRef.current.removeEventListener("cancel", handleUseImage);
    }
  }
}, [imgName]);
about 4 years ago · Santiago Trujillo 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