DavidWells / analytics

Lightweight analytics abstraction layer for tracking page views, custom events, & identifying visitors
https://getanalytics.io
MIT License
2.45k stars 244 forks source link

useAnalytics.page() doesn't send an event type to GTM #148

Open roballsopp opened 3 years ago

roballsopp commented 3 years ago

I'm trying to track page views in my React app by using the hook provided by this package. Here's my basic setup:

import * as React from 'react'
import Analytics from 'analytics'
import {AnalyticsProvider as UseAnalyticsProvider} from 'use-analytics'
import googleTagManager from '@analytics/google-tag-manager'

const init = Analytics({
    app: 'sense-dashboard',
    plugins: [
        googleTagManager({
            containerId: GTAG_CONTAINER_ID,
        }),
    ],
})

const AnalyticsProvider = ({children}: Children) => {
    return (
        <UseAnalyticsProvider instance={init}>
            <App />
        </UseAnalyticsProvider>
    )
}

const App = () => {
    const location = useLocation()
    const {page} = useAnalytics()

    React.useEffect(() => {
        page()
    }, [location, page])

    ...
}

This doesn't seem to register page views in Google Tag Manager, because no event type is sent with the page() call. If I change it to this:

const App = () => {
    const location = useLocation()
    const {page} = useAnalytics()

    React.useEffect(() => {
        page({event: 'Pageview'})
    }, [location, page])

    ...
}

Then everything works as expected. It took a lot of digging to uncover this issue though, and I definitely expected this to be the default behavior. Is this intended behavior? Is there something I'm missing in my set up that would have made this work?

DavidWells commented 3 years ago

Looks like a similar issue as https://github.com/DavidWells/analytics/issues/147#issuecomment-784425598

Double check your dataLayer is being pushed to and that your google tag manager is wired up correctly in GTM.

https://getanalytics.io/plugins/google-tag-manager/#configuring-gtm

roballsopp commented 3 years ago

My dataLayer is being pushed to when I call page(), but the object that is pushed is missing the event property entirely, whereas all the other items in window.dataLayer have an event property. Here's a log of window.dataLayer before and after I call page(). I would expect the new entry to have an event property, but you can see it doesn't:

image

johnparn commented 3 years ago

Hi,

and thanks for this nice library!

I've had a similar issue with GTM, no events where fired and they didn't show up in the dataLayer. After some debugging I spotted an issue with initialisation happening twice. On the second time the dataLayer-property in the config was set to to `undefined´, hence the track method was executed but nothing vital happened as there is check that dataLayer is defined.

As init was run twice I reckoned the error was on my side and I changed the tracking component accordingly, which works for me. Hope it can be of assistance:

// GTM
const googleTagManagerSettings = () =>
  googleTagManager({
    containerId: process.env.REACT_APP_GTM,
    enabled: false,
  });

// GA - yup not running GA through GTM yet
const googleAnalyticsSettings = () =>
  googleAnalytics({
    enabled: false,
    trackingId: process.env.REACT_APP_GA_ID,
    anonymizeIp: true,
    customDimensions: {
      source: 'dimension1',
      itemTitle: 'dimension2',
      lang: 'dimension3',
    },
    setCustomDimensionsToPage: false,
    // debug: true,
  });

const analyticsSettings = {
  app: `myAppName`,
  plugins: [googleTagManagerSettings(), googleAnalyticsSettings()],
  debug: true,
};

const Tracking = ({ children }) => {
  const consentContext = useContext(ConsentContext);
  const analytics = Analytics(analyticsSettings);

  // Consented to statistical data
  if (consentContext.has('statistical')) {
    analytics.plugins.enable('google-tag-manager');
    analytics.plugins.enable('google-analytics');
  }

  if (!analytics) return null;

  return (
    <AnalyticsProvider instance={analytics}>
      {children}
    </AnalyticsProvider>
  );
};
roballsopp commented 3 years ago

Now that I've worked with this for a bit longer, I'm realizing there isn't really an official Pageview event, but it looks like the universal analytics tag for GA fires when it sees a gtm.js event type.

DavidWells commented 3 years ago

Yeah, it's dependant on how you wire things up in google tag manager, and everyone has a different flavor of that.

I found this post helpful when I was setting up GTM a while back https://www.bounteous.com/insights/2018/03/30/single-page-applications-google-analytics/

TBH I've personally moved away from GTM because it's too complicated with stuff like this and because my analytics changes are no longer living in/close to source control.

I will add the link to the docs for tracking virtual page views