Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Last active July 27, 2022 03:00
Show Gist options
  • Select an option

  • Save dpaluy/2d60918db0c4d37820d1080fa773ac14 to your computer and use it in GitHub Desktop.

Select an option

Save dpaluy/2d60918db0c4d37820d1080fa773ac14 to your computer and use it in GitHub Desktop.
Frontend Analytics
// Google Analytics
class GoogleAnalytics {
constructor() {
this.ga = typeof window.ga === 'function' ? window.ga : () => null;
}
pageView = (params) => {
setTimeout(() => this.ga('send', params, window.location.pathname));
}
event = (params) => {
const eventParams = { ...params, hitType: 'event' };
setTimeout(() => this.ga('send', eventParams));
}
}
// Heap Analytics
class Heap {
constructor() {
this.track = window.heap ? window.heap.track : () => null;
}
pageView = (params) => {
setTimeout(() => this.track(params, { url: window.location.pathname }));
}
event = (params) => {
setTimeout(() => this.track('event', params));
}
}
const sendAnalytics = (params = {}) => {
const ga = new GoogleAnalytics();
const heap = new Heap();
if (typeof params === 'string' && params === 'pageview') {
ga.pageView(params);
heap.pageView(params);
} else {
ga.event(params);
heap.event(params);
}
};
export default sendAnalytics;
import analytics from 'config/analytics';
// Action tracking example
export const endorsementSkip = () =>
(dispatch) => {
dispatch(endorsementSkipStart());
analytics({ eventCategory: 'Endorsements', eventAction: 'Skipped' });
apiClient.post('/my/endorsements/skip')
.then(
(data) => dispatch(endorsementSkipSuccess(data)),
(error) => dispatch(endorsementSkipFailure(error))
);
};
import { BrowserRouter } from 'react-router-dom';
import analytics from 'config/analytics';
class Application extends PureComponent {
onRouteChange = (currentProps, nextProps) => {
if (!nextProps || (currentProps.location.pathname !== nextProps.location.pathname)) {
analytics('pageview');
}
}
render() {
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment