Created
May 2, 2022 15:47
-
-
Save erkobridee/e7662195827d6befd5308cb7516c3f89 to your computer and use it in GitHub Desktop.
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 characters
import * as React from 'react'; | |
import { useRouter } from 'next/router'; | |
//----------------------------------------------------------------------------// | |
const isBrowser = window !== undefined; | |
type Gtag = (...args: any[]) => void; | |
export interface IGoogleAnalyticsPageView { | |
page_title?: string; | |
page_location?: string; | |
page_path: URL | string; | |
} | |
//----------------------------------------------------------------------------// | |
export const gtag: Gtag = (...args) => { | |
if (!isBrowser || !window['gtag']) return; | |
window['gtag'](args[0], args[1], args[3]); | |
}; | |
export const event = (action: string, values: any) => { | |
gtag('event', action, values); | |
}; | |
export const pageView = (param: IGoogleAnalyticsPageView) => { | |
event( | |
'page_view', | |
Object.entries(param) | |
.filter((entry) => !!entry[1]) | |
.reduce((acc, entry) => { | |
acc[entry[0]] = entry[1]; | |
return acc; | |
}, {}) | |
); | |
}; | |
//----------------------------------------------------------------------------// | |
const EVENT_NAME = 'routeChangeComplete'; | |
export const GALogRouteChange: React.FunctionComponent = () => { | |
const router = useRouter(); | |
React.useEffect(() => { | |
const handleRouteChange = (url: URL) => { | |
pageView({ page_path: url }); | |
}; | |
router.events.on(EVENT_NAME, handleRouteChange); | |
return () => { | |
router.events.off(EVENT_NAME, handleRouteChange); | |
}; | |
}, [router.events]); | |
return null; | |
}; | |
export default GALogRouteChange; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment