FormidableLabs / react-swipeable

React swipe event handler hook
https://commerce.nearform.com/open-source/react-swipeable
MIT License
1.99k stars 146 forks source link

document swipe on one page in SPA causes multiple event handlers #322

Closed tomasz13nocon closed 1 year ago

tomasz13nocon commented 1 year ago

I'd like to have a document wide swipe event only on one page in an SPA. When on that page, I want the swipe to work on components that are shared across multiple pages, so it needs to be on document. When navigating between pages the swipe events don't get removed and new ones get added.

Maybe a cleanup function could be provided, which could be returned in useEffect.

Reproduction: https://codesandbox.io/s/react-swipeable-event-stacking-pcrw2o?file=/src/Page.js Go between "Home" and "Other page" a couple of times, then swipe left or right and see console output. These stale events also fire when swiping in "Home" even tough they have no effect in this example since they close over an unmounted component.

hartzis commented 1 year ago

briefly looking at the issue and code and knowing how the ref method works you could possibly try returning a function in the setup useEffect that "calls" ref with an empty object to trigger the clean up method internally


React.useEffect(() => {
    ref(document);
    return () => ref({});
  });
tomasz13nocon commented 1 year ago

Indeed that fixes the issue. Thank you very much!