Ad

React SPA - GTM Analytics React-Helmet Previous Page Title

I am using Google Tag Manager to push pageview events to the datalayer for Analytics tracking. This is happening in componentDidMount() (and sometimes componentWillReceiveProps() if I am listening for query string parameter changes with the location prop using withRouter).

I am using react-helmet to dynamically update my title and other tags as components change.

I have noticed an issue that I am getting the improper page title in Analytics. It's frequently showing the page title of the previous page, instead of the one I am currently on. It appears that react-helmet is not updating the tag until after componentDidMount().

Page View Event Function Example

My analytics tag in GTM is called every time this event is pushed to the data layer

const firePageViewEvent = () => {
      console.log("Pageview event fired (from tracking script)");

      if (window && window.dataLayer) {
          console.log("window and dataLayer exist, pushing pageview event.");
          let dataLayer = window.dataLayer || [];
          dataLayer.push({
              'event': 'reactPageViewEvent'
          });
      } else {
          console.log("window or dataLater does not exist, cannot push pageview event.");
      }
};

Ad

Answer

I can confirm that wrapping the function in a setTimeOut() function with a 0ms delay does indeed work to ensure that the event is only pushed after react-helmet has a chance to do its thing.

This allows me to consistently get the current page title in Analytics.

See github issue comment

Updated Function

const firePageViewEvent = () => {
    setTimeout(() => {
        console.log("Pageview event fired (from tracking script)");

        if (window && window.dataLayer) {
            console.log("window and dataLayer exist, pushing pageview event.");
            let dataLayer = window.dataLayer || [];
            dataLayer.push({
                'event': 'reactPageViewEvent'
            });
        } else {
            console.log("window or dataLater does not exist, cannot push pageview event.");
        }
    }, 0);
};

Ad
source: stackoverflow.com
Ad