Skip to content
Advertisement

Prevent Event Listener firing event multiple times

I am using this event listener to fire an event which basically updates my state of Interval in a useEffect and enabling me to go up and down in my table. The up and down approach working fine for me but its firing the event multiple times. This multiple times firing of event causing the top and down events works slow and slows over all application.

  useEffect(() => {
    console.log("HAAN MEI WUHI PAPPI HUN");
    document.addEventListener("keyup", (e) => {
      if (e.shiftKey && e.code === "ArrowRight") {
        console.log("shift + right", vjsRef.current.currentTime);
        vjsRef.current.currentTime = vjsRef.current.currentTime + 1;
      } 
      else if (e.shiftKey && e.code === "ArrowLeft") {
        console.log("fire! left", vjsRef.current.currentTime);
        vjsRef.current.currentTime = vjsRef.current.currentTime - 1;
      }
    });

    document.addEventListener("keyup", async(event) => {
      if (event.code === "ArrowUp") {
        console.log('aj mei upar ');
        await props.setSelectInterval(props.selectInterval - 1);
      }
      if (event.code === "ArrowDown") {
        if (props.selectInterval + 1 < props.row.length) {
          console.log('asmaan nichay');
          props.setSelectInterval(props.selectInterval + 1);
        }
      }
    });
  }, []);

enter image description here

enter image description here

Advertisement

Answer

useEffect(() => {
    var foo1 = (e) => {
      if (e.code === "ArrowUp") {
        if (props.selectInterval - 1 >= 0) {
          props.setSelectInterval(props.selectInterval - 1);
        }
      }
      if (e.code === "ArrowDown") {
        if (props.selectInterval + 1 < props.row.length) {
          props.setSelectInterval(props.selectInterval + 1);
        }
      }
    };
    document.addEventListener("keyup", foo1);
return () => {
      document.removeEventListener("keyup", foo1);
    };
  }, [props.selectInterval]);

well this works for me! thanks to both contributors above!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement