Skip to content

Instantly share code, notes, and snippets.

@donavon
Created October 23, 2021 14:31
Show Gist options
  • Save donavon/a44ace5338f192eca200e5a10760aeba to your computer and use it in GitHub Desktop.
Save donavon/a44ace5338f192eca200e5a10760aeba to your computer and use it in GitHub Desktop.
onLocationChange isn't being called
// 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