In our React app on localhost, the app returns the following 2 warnings:
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?