Created
October 23, 2021 14:31
-
-
Save donavon/a44ace5338f192eca200e5a10760aeba to your computer and use it in GitHub Desktop.
onLocationChange isn't being called
This file contains 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
// set page tracking for Single Page Applications | |
// see https://developers.google.com/analytics/devguides/collection/gtagjs/single-page-applications | |
import { createBrowserHistory, Update } from 'history'; // 5.0.1 | |
import { useEffect } from 'react'; | |
const history = createBrowserHistory(); | |
const onLocationChange = ({ location }: Update) => { | |
const { gtag } = window; | |
const { pathname, search } = location; | |
const pagePath = `${pathname}${search}`; | |
console.log('pagePath', pagePath); | |
if (!gtag) return; | |
gtag('set', { | |
page_path: pagePath, | |
}); | |
gtag('event', 'page_view'); | |
}; | |
export const useTrackPageView = () => { | |
useEffect(() => { | |
console.log('useTrackPageView'); | |
const unlisten = history.listen(onLocationChange); | |
return unlisten; | |
}, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment