Last active
June 18, 2022 02:39
-
-
Save tmarshall/b5433a2c2acd5dbfc592bbc4dd4c519c to your computer and use it in GitHub Desktop.
Revisions
-
tmarshall revised this gist
Apr 22, 2021 . 2 changed files with 30 additions and 33 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,33 +0,0 @@ This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,30 @@ /* see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon ```jsx const MyComponent = ({ children }) => { // will get fired if the page unloads while the component is mounted useUnloadBeacon({ url: 'https://api.my.site/route', payload: () => { return 'something' } }) return children } ``` */ import { useEffect } from 'react' export default function useUnloadBeacon({ url, payload = () => {} }) { const eventHandler = () => navigator.sendBeacon(url, payload()) useEffect(() => { window.addEventListener('unload', eventHandler, true) return () => { window.removeEventListener('unload', eventHandler, true) } }, []) } -
tmarshall created this gist
Feb 2, 2020 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,33 @@ import { useEffect } from 'react' // see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon /* <UnloadBeacon url='https://api.my.site/route' payload={() => { return 'something' }} > <div>some content</div> </UnloadBeacon> */ const UnloadBeacon = ({ url, payload = () => {}, children }) => { const eventHandler = () => navigator.sendBeacon(url, payload()) useEffect(() => { window.addEventListener('unload', eventHandler, true) return () => { window.removeEventListener('unload', eventHandler, true) } }, []) return children } export default UnloadBeacon