Warning: ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually

Viewed 378

I am using React GA to track analytics. Two useEffect hooks, first one to check condition (do not initialize if in dev, on localhost). The second useEffect to track pageview. I am getting a warning

ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually.

How do I ensure that ReactGA.initialize is called first?

import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import ReactGA from "react-ga";
import { GA_TRACKING_NUMBER } from './config/google';
import APP from './config/constants';

const GoogleAnalytics = () => {
    const location = useLocation();
    const [initialized, setInitialized] = useState(false);

    useEffect(() => {
        if (!window.location.href.includes("localhost")) {
            // initializing Google Analytics:
            ReactGA.initialize(GA_TRACKING_NUMBER, { debug: APP.isDevMode });
        }
        setInitialized(true);
    }, []);

    useEffect(() => {
        if (initialized) {
            ReactGA.pageview(location.pathname + location.search);
        }
    }, [initialized, location]);
    
    return null;
};

export default GoogleAnalytics;
1 Answers

You can try adding a promise to ensure loading finishes first, a generic example could be this:

const trackingID = "UA-XXXXXXXXX-1";
new Promise(resolve => {
  (function(i, s, o, g, r, a, m) {
    i.GoogleAnalyticsObject = r;
    (i[r] =
      i[r] ||
      function() {
        (i[r].q = i[r].q || []).push(arguments);
      }),
      (i[r].l = 1 * new Date());
    (a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]);
    a.async = 1;
    a.src = g;
    a.addEventListener("load", resolve);
    m.parentNode.insertBefore(a, m);
  })(
    window,
    document,
    "script",
    "https://www.google-analytics.com/analytics.js",
    "ga"
  );
  window.ga("create", trackingID, "auto");
  window.ga("send", "pageview");
}).then(() => {
  ReactGA.initialize(trackingID, {
    standardImplementation: true
  });
  ReactGA.pageview('/index.html');
});
Related