Home > Software design >  Event Listener is not removing
Event Listener is not removing

Time:08-04

I am trying to remove the Event Listener that i created but unable to do that, don't know where I am going wrong. Any help is highly appreciated.

const [windowEvent, setWindowEvent] = useState(false);

function handleClick(){
  alert("Mouse Pressed!!");
}

useEffect(function(){

  if(!windowEvent){
    window.removeEventListener("dblclick",handleClick);
  }
  else{
    window.addEventListener("dblclick",handleClick);
  }
},[windowEvent]);
return (
  <div>
    <button onClick={() => setWindowEvent(prevState => !prevState)}>Toggle Window Event</button>
    {windowEvent && <WindowEvent />}
  </div>
)

CodePudding user response:

If your Effect subscribes to something, you need a cleanup function that should unsubscribe.

  useEffect(
    function () {
      if (windowEvent) {
        window.addEventListener("dblclick", handleClick);
      } 

      return () => window.removeEventListener("dblclick", handleClick);
    },
    [windowEvent]
  );

React beta docs explains clearly how to subscribe to events

Edit Removed useless else statement

CodePudding user response:

useEffect(function(){
    window.addEventListener("dblclick",handleClick);
    return  () => window.removeEventListener("dblclick",handleClick);
},[windowEvent]);

CodePudding user response:

The "dblclick" event does not exist on the window object, as can be seen in this list. You can only do it on elements.

  • Related