0

I want to track users by their login ID in a ReactJS application. I followed all of the tutorials on the documentation to set up the User Id View. I enabled userId tracking in google analytics and I've set a userId upon logging in. this is my login function :

  const accessToken = data.data.accessToken;
      sessionStorage.setItem("accessToken", accessToken);
      localStorage.setItem("userId", data.data.data.user._id);
      console.log(typeof(data.data.data.user._id));
      
      // set UserId with reactGa
      ReactGa.set({ userId: data.data.data.user._id });
      navigate("/gaLogin");

I've initialized react-ga in my layout component and it works fine with other normal views. but in the userId view it doesn't work and it shows nothing (0 active users...) Idk if it's related to React or I'm doing something wrong.

PS: sometimes it detect a user upon logging in and it stops tracking right after.

  • What documentation are you following? that doesn't look like code use to add hits to google analytics. – Linda Lawton - DaImTo May 17 '22 at 11:05
  • @DaImTo I'm using a npm package called React-ga: [link](https://github.com/react-ga/react-ga) – Hazem Ben Abdelhafidh May 17 '22 at 11:08
  • but whats the access token for? you dont use an access token to track hits to google analytics. Check the README on that page and you will see how to use it. – Linda Lawton - DaImTo May 17 '22 at 11:10
  • @DaImTo the code I included is for the login function(upon success) I implemented you can ignore the accessToken lines. the api is returning the data variable from which i get the userId then set it with ReactGa.set({ userId: data.data.data.user._id }) – Hazem Ben Abdelhafidh May 17 '22 at 12:50
  • okay and what do you mean by this then "userId view"? Maybe i should ask how do you know its not working? – Linda Lawton - DaImTo May 17 '22 at 12:50
  • @DaImTo when you enable user Id tracking you're prompted to create a new seperate view in order to collect the data of users who logged in. I just called it "userId view" and it's just means the view responsible of collecting the date of users who connected to your website via an authentication system. I hope that's clear – Hazem Ben Abdelhafidh May 17 '22 at 13:53

1 Answers1

0

The following is working for me, as used in the top level parent component.

First

import ReactGA from "react-ga4";

Then

useEffect(() => {
        if (isCookieConsent && initialised) {
          ReactGA.initialize("ga4-someid-1", {
            gaOptions: {
              userId: user ? user.id : "n/a",
            },
          });
          ReactGA.send("pageview");
        }
}, [user, pathname, isCookieConsent, initialised]);

Then create a user-explorer view to see the analytics https://support.google.com/analytics/answer/9283607#zippy=%2Cin-this-article

Diokas
  • 21
  • 2