Google analytics UserId view is not working with react

746 views Asked by At

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.

1

There are 1 answers

0
Diokas On

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