Search code examples
reactjsreact-router-v4react-ga

React-ga not computing first access


I have React-ga set up with React Router in the following manner:

...
import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import {Provider} from 'react-redux';
import ReactGA from 'react-ga';

ReactGA.initialize('MY TRACKING CODE', {
  debug: true
});

const history = createHistory();
history.listen((location) => {
  ReactGA.set({ page: location.pathname });
  ReactGA.pageview(location.pathname);
});


ReactDOM.render((
  <Provider store={store}>
    <Router history={history}>
      <Layout />
    </Router>
  </Provider>
), document.getElementById('root'));
registerServiceWorker();

if I'm already on the page and access another path, I get the following on the console:

 log.js:2 [react-ga] called ga('set', fieldsObject);
 log.js:2 [react-ga] with fieldsObject: {"page":"/products"}
 log.js:2 [react-ga] called ga('send', 'pageview', path);
 log.js:2 [react-ga] with path: /products

However, if I access the page for the first time (by clicking on a link or typing the path directly on the browser), I don't get anything on the console.

Is there any step that I'm missing in order to compute the first access?


Solution

  • For anyone having the same problem, the issue was that history listen is not called on initial page load since it's only called when the location changes.

    The following setup worked for me:

    ...
    import { Router } from 'react-router-dom';
    import createHistory from 'history/createBrowserHistory';
    import {Provider} from 'react-redux';
    import ReactGA from 'react-ga';
    
    const trackPageView = location => {
      ReactGA.set({ page: location.pathname });
      ReactGA.pageview(location.pathname);
    };
    
    const initGa = history => {
      ReactGA.initialize('MY TRACKING CODE', {
        debug: true
      });
      trackPageView(history.location);
      history.listen(trackPageView);
    };
    
    const history = createHistory();
    initGa(history);
    
    ReactDOM.render((
      <Provider store={store}>
        <Router history={history}>
          <Layout />
        </Router>
     </Provider>
    ), document.getElementById('root'));
    registerServiceWorker();