0

In our React app on localhost, the app returns the following 2 warnings:

enter image description here

To setup GA in react, we are trying to use our usePageTracking hook. From How to set up Google Analytics for React-Router?

usePageTracking

import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import ReactGA from 'react-ga';
import config from '../config';

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

    useEffect(() => {
        if (!window.location.href.includes('localhost')) {
            ReactGA.initialize(config.gaTrackingId);
        }
        setInitialized(true);
    }, []);

    useEffect(() => {
        if (initialized) {
            ReactGA.pageview(location.pathname + location.search);
            // ReactGA.set({ userId: userId }); // don't have userId in usePageTracking
        }
    }, [initialized, location]);
};

export default usePageTracking;

With this hook in our App.js file, we call the hook, and then we check if a user is already logged in (auth-token in localStorage), and while grabbing the user info, the code (attempts to) sets the userId in ReactGA with ReactGA.set.

App.js

import React, { useState, useEffect } from 'react';
import usePageTracking from './hooks/usePageTracking';

function App() {
    usePageTracking();

    // Check User Is Logged In
    useEffect(() => {
        const checkLoggedIn = async () => {
            // Grab Auth Token From Local Storage
            let token = localStorage ? localStorage.getItem('auth-token') : window.localStorage.getItem('auth-token');
            if (token === null) {
                localStorage.setItem('auth-token', '');
                token = '';
            }

            try {
                // Check If Valid Token
                const apiBaseUrl = config.url.API_URL;
                const tokenResponse = await Axios.post(`${apiBaseUrl}/users/tokenIsValid`, null, { headers: { 'x-auth-token': token } });
                // if valid token exists...
                if (tokenResponse.data) {
                    // get the user
                    const userRes = await Axios.get(`${apiBaseUrl}/users/`, {
                        headers: { 'x-auth-token': token }
                    });

                    // Set userId for Google Analytics
                    ReactGA.set({ userId: userRes.data._id });

                    // And Set User Data, Giving User Logged-In Access
                    setIsUserLoading(false);
                    setUserData({ token, user: userRes.data });
                } else {
                    setIsUserLoading(false);
                }
            } catch (err) {
                setIsUserLoading(false);
            }
        };

        checkLoggedIn();
    }, []);

    // render rest of the app...
    // ...
}

How can the code be revised to resolve these warnings? Presumably React GA is not setup properly since these 2 warnings are thrown?

Canovice
  • 9,012
  • 22
  • 93
  • 211

1 Answers1

1

You are only initializing if it's not localhost but setting initialized to true;

if (!window.location.href.includes('localhost')) {
   ReactGA.initialize(config.gaTrackingId);
}
setInitialized(true) // for localhost we never invoked ReactGA.initialize

So on localhost, without initializing the library there is a call to ReactGA.pageview, therefore the error message, ReactGA.initialize should be called first.

You should include a check for localhost when calling pageview.

if (!window.location.href.includes('localhost') && initialized) {
   ReactGA.pageview(location.pathname + location.search);
}
A G
  • 21,087
  • 11
  • 87
  • 112
  • Great observation. It seems like I could also move the `setInitialized(true)` into the initial if() statement just below `ReactGA.initialize()` – Canovice May 29 '22 at 15:53