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.");
}
};
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.
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);
};
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?