Why isn't my JS eventlistener triggering a function?

19 Views Asked by At

I am working on a simple React app in which I have a basket that stores the number of items a user wants to purchase.

I'm storing this number in localstorage and that all works fine.

I'd now like to use that same number to populate the trolley icon at the top of my page. This lives in the main React App component.

I've set up an event listener in the main App component as so:

useEffect(() => {

  window.addEventListener("su", handleCartUpdate(), false)
  
  return () => {
    document.removeEventListener("su", handleCartUpdate(), false);    
  };
}, []); 

This will only fire on initiation but, if I understand eventlisteners correctly, the listener will persist.

After writing the number to localstorage, I fire an event from the product page component which I assumed would be picked up by the eventlistener I set up previously:

const e = new Event("su");
window.dispatchEvent(e);

My problem is that the event doesn't seem to be picked up by the listener. Does anyone know why this is, please?

0

There are 0 best solutions below