Stop double-counting page vies

This commit is contained in:
Seth Call 2025-03-25 07:03:51 -05:00
parent cfe0129a6d
commit cc664889f8
1 changed files with 24 additions and 7 deletions

View File

@ -2,19 +2,36 @@ import ReactGA from "react-ga4";
var initialized = false;
// Noticed that ReactGA.initialize logs a page view,
// so the 1st logPageView will end up double-counting the initial path landed on
var ignoredFirstPageView = false;
export const initGA = () => {
if(process.env.REACT_APP_GOOGLE_ANALYTICS_ID) {
ReactGA.initialize(process.env.REACT_APP_GOOGLE_ANALYTICS_ID);
initialized = true;
try {
if (process.env.REACT_APP_GOOGLE_ANALYTICS_ID) {
ReactGA.initialize(process.env.REACT_APP_GOOGLE_ANALYTICS_ID);
initialized = true;
} else {
initialized = false;
console.log("no GA ID found");
}
}
else {
initialized = false;
console.log("no GA ID found");
catch (error) {
console.log("Error initializing GA", error);
}
};
export const logPageView = (path) => {
if(initialized) {
ReactGA.send({hitType: "pageview", page: path});
if(ignoredFirstPageView) {
try {
ReactGA.send({hitType: "pageview", page: path});
}
catch(error) {
console.log("Error logging page view", error);
}
else {
ignoredFirstPageView = true;
}
}
};