fix: report every page view from the route effect
The route effect ran before App initialized react-ga4, so its first page view was dropped and the landing page was only counted by gtag's automatic page_view. - initialize react-ga4 once at module load - pass send_page_view: false and send one page view per route change - include the query string in the page path - only track production builds
This commit is contained in:
+13
-5
@@ -10,11 +10,22 @@ import News from './features/news/News';
|
|||||||
import PageTitle from './features/page-title/PageTitle';
|
import PageTitle from './features/page-title/PageTitle';
|
||||||
import Search from './features/search/Search';
|
import Search from './features/search/Search';
|
||||||
|
|
||||||
|
const GOOGLE_ANALYTICS_TRACKING_ID = 'G-T4L3SDCN6P';
|
||||||
|
const isAnalyticsEnabled = import.meta.env.PROD;
|
||||||
|
|
||||||
|
if (isAnalyticsEnabled) {
|
||||||
|
// Page views are sent from the location effect in AppMain, the first one included;
|
||||||
|
// gtag's own page_view on config would count the landing page twice.
|
||||||
|
ReactGA.initialize(GOOGLE_ANALYTICS_TRACKING_ID, { gtagOptions: { send_page_view: false } });
|
||||||
|
}
|
||||||
|
|
||||||
const AppMain: React.FC = () => {
|
const AppMain: React.FC = () => {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
ReactGA.send({ hitType: 'pageview', page: location.pathname });
|
if (isAnalyticsEnabled) {
|
||||||
}, [location]);
|
ReactGA.send({ hitType: 'pageview', page: location.pathname + location.search });
|
||||||
|
}
|
||||||
|
}, [location.pathname, location.search]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.container}>
|
<div className={styles.container}>
|
||||||
@@ -51,9 +62,6 @@ const AppMain: React.FC = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const App: React.FC = () => {
|
const App: React.FC = () => {
|
||||||
React.useEffect(() => {
|
|
||||||
ReactGA.initialize('G-T4L3SDCN6P');
|
|
||||||
}, []);
|
|
||||||
return (
|
return (
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<AppMain />
|
<AppMain />
|
||||||
|
|||||||
Reference in New Issue
Block a user