Skip to content

Instantly share code, notes, and snippets.

@rw3iss
Created June 25, 2022 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rw3iss/3fb0237909203bfcf9eccfff3b27bf90 to your computer and use it in GitHub Desktop.
Save rw3iss/3fb0237909203bfcf9eccfff3b27bf90 to your computer and use it in GitHub Desktop.
GA4 Google Analytics Class
/**
* @author pybymantis@gmail.com (Daniel Kennedy)
* @copyright Copyright (c) 2021, AdCloud
* @description GoogleAnalyticsService
*/
// https://support.google.com/analytics/answer/9213390?hl=en&utm_id=ad#zippy=%2Cin-this-article
// https://www.npmjs.com/package/ga-4-react
// ga4.gtag('event','pageview','path')
// https://developers.google.com/analytics/devguides/collection/analyticsjs/custom-dims-mets
import GA4React from 'ga-4-react';
import { GA4ReactResolveInterface } from 'ga-4-react/dist/lib/gtagModels';
class GoogleAnalyticsService {
currentUser = JSON.parse(localStorage.current_user || '{}');
event = ({ event, options }) => {
switch (GA4React.isInitialized()) {
case true:
const ga4 = GA4React.getGA4React();
if (ga4) {
ga4.gtag('event', event, options);
}
break;
default:
case false:
const ga4react = new GA4React('G-S17TY6VBS7');
ga4react.initialize().then(
(ga4: GA4ReactResolveInterface) => {
ga4.gtag('event', event, options);
},
(err: Error) => {
console.error(err);
}
);
break;
}
};
pageview = (path) => {
this.pageviewEvent({ path: path });
};
pageviewEvent = ({ path }) => {
let options = {
uid: this.currentUser._id,
page_path: path
};
let props = { event: 'page_view', options: options };
this.event(props);
};
loginEvent = () => {
let options = {
method: 'Google',
uid: this.currentUser._id
};
let props = { event: 'login', options: options };
this.event(props);
};
login = () => {
console.log('Login Event');
this.loginEvent();
};
}
export default new GoogleAnalyticsService();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment