Reputation: 1905
I have a working useEffect
to call my google analytics when changing page.
This works fine when changing pages but when you initially load for the first time or refresh it does not call the router.events.on
this is my code
useEffect(() => {
if (cookies === true) {
router.events.on("routeChangeComplete", () => {
ReactGA.pageview(window.location.pathname);
});
return () => {
router.events.off("routeChangeComplete", () => {
ReactGA.pageview(window.location.pathname);
});
};
}
}, [router.events]);
I thought of using an other useEffect
to initially call the reactGA but then when changing page it would be called twice, which is not good.
any idea on how to make this work on the initial page load?
Upvotes: 4
Views: 4581
Reputation: 50318
That's expected behaviour - router.events
is only triggered on client-side page navigations initiated by the Next.js router.
You can call ReactGA.pageview
on a separate useEffect
to handle initial page loads.
useEffect(() => {
if (cookies === true) {
ReactGA.pageview(window.location.pathname);
}
}, []);
Upvotes: 5