nytimes / react-tracking

🎯 Declarative tracking for React apps.
https://open.nytimes.com/introducing-react-tracking-declarative-tracking-for-react-apps-2c76706bb79a
Other
1.88k stars 123 forks source link

window.dataLayer is undefined #111

Closed apatt124 closed 5 years ago

apatt124 commented 5 years ago

It seems that the dataLayer is not being initialized in src/dispatchTrackingEvent.js. After I trigger events through any @track decorator, when I log window.dataLayer, it show up in the console as undefined. See below:

import React, { Component } from 'react';
import track from "react-tracking";
import '../../App.scss';
import './locator.scss';
import LocatorContent from '../../Components/LocatorContent'
import Search from '../../Components/Search/Search'

@track({ page: 'Locator' })
class Locator extends Component {

  @track({ action: 'click' })
  handleClick = () => {
    // setTimeout ensures the console.log happens after dataLayer has been updated
    // so that we can inspect the data that was pushed
    setTimeout(() => { 
      console.log(window);
      console.log('click track', window.dataLayer);
    }, 0);
  };
  render() {
    return (
      <div className="Locator"
        onClick={this.handleClick}
      >
        <Search/>
        <LocatorContent/>
      </div>
    );
  }
}

export default Locator;
saidkholov commented 5 years ago

I think you need to add/link tracking library like GA or GTM. React-tracking is analytics platform agnostic.

tizmagik commented 5 years ago

The default dispatch should create the dataLayer array if it’s not there. Can you create a codesandbox repro? I’m not able to reproduce the issue

juliusdelta commented 5 years ago

In my work project we initialize window.dataLayer as an empty array if it doesn't exist. e.g.

window.dataLayer = window.dataLayer || [];