Skip to content

Instantly share code, notes, and snippets.

@phunkren
Last active April 25, 2020 12:05
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 phunkren/006f9e9b0ce96cf33c55d8c5440c0165 to your computer and use it in GitHub Desktop.
Save phunkren/006f9e9b0ce96cf33c55d8c5440c0165 to your computer and use it in GitHub Desktop.
"Segment as a Service" /s
REACT_APP_SEGMENT_WRITE_KEY=dUmmYK3yTh@tisnaeReel
import React from 'react';
export function App() {
const segmentService = useSegment();
handleButtonClick() {
segmentService.trackEvent('Button clicked');
}
return (
<main>
<h1>Segment as a Service</h1>
<button onClick={handleButtonClick}>CLick me</button>
</main>
);
};
interface TrackPageView {
category?: string;
name: string;
properties?: object;
options?: object;
callback?: () => void;
}
interface TrackEvent {
event: string;
properties?: object;
options?: object;
callback?: () => void;
}
interface IdentifyUser {
id?: string | null;
traits?: object;
options?: object;
callback?: () => void;
}
export class SegmentService {
// https://github.com/segmentio/analytics-react#-step-3-identify-users
identifyUser({ id = null, traits = {}, options, callback }: IdentifyUser) {
window.analytics.identify(id, traits, options, callback);
}
// https://github.com/segmentio/analytics-react#-step-2-track-page-views-in-an-spa
trackPageView({
category,
name,
properties = {},
options,
callback,
}: TrackPageView) {
window.analytics.page(category, name, properties, options, callback);
}
// https://github.com/segmentio/analytics-react#track-calls-with-event-handlers
trackEvent({ event, properties = {}, options, callback }: TrackEvent) {
window.analytics.track(event, properties, options, callback);
}
}
import { useState, useEffect, useContext, useMemo } from 'react';
import { LocationContext } from 'src/contexts/location';
import { SegmentService } from 'src/services/segment';
export const useSegment = () => {
const [isInit, setIsInit] = useState(false);
const { pathname } = useContext(LocationContext);
const service = useMemo(() => {
return isInit ? new SegmentService() : null;
}, [isInit]);
function initSegment(writeKey: string) {
const analytics = (window.analytics = window.analytics || []);
if (!analytics.initialize && !analytics.invoked) {
analytics.invoked = !0;
analytics.methods = [
'trackSubmit',
'trackClick',
'trackLink',
'trackForm',
'pageview',
'identify',
'reset',
'group',
'track',
'ready',
'alias',
'debug',
'page',
'once',
'off',
'on',
];
analytics.factory = function(t) {
return function() {
const e = Array.prototype.slice.call(arguments);
e.unshift(t);
analytics.push(e);
return analytics;
};
};
for (let t = 0; t < analytics.methods.length; t++) {
const e = analytics.methods[t];
analytics[e] = analytics.factory(e);
}
analytics.load = function(t, e) {
const n = document.createElement('script');
n.type = 'text/javascript';
n.async = !0;
n.src = `https://cdn.segment.com/analytics.js/v1/${t}/analytics.min.js`;
const a = document.getElementsByTagName('script')[0];
a.parentNode.insertBefore(n, a);
analytics._loadOptions = e;
};
analytics.SNIPPET_VERSION = '4.1.0';
analytics.load(`${writeKey}`);
}
}
/* Inject Segment script tag */
useEffect(() => {
initSegment(process.env.REACT_APP_SEGMENT_WRITE_KEY);
setIsInit(true);
}, []);
/* Trigger Segment page update whenever url changes */
useEffect(() => {
if (isInit) {
service.trackPageView({ name: pathname });
}
}, [isInit, service, pathname]);
return service;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment