Skip to content

Instantly share code, notes, and snippets.

@lukebussey
Created October 17, 2021 00:11
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 lukebussey/d2a5d4a71bbbbb26fa2e05c43773be97 to your computer and use it in GitHub Desktop.
Save lukebussey/d2a5d4a71bbbbb26fa2e05c43773be97 to your computer and use it in GitHub Desktop.
import PropTypes from 'prop-types';
import { useState, useEffect, useContext, createContext } from 'react';
import { useRouter } from 'next/router';
import merge from 'deepmerge';
import usePrevious from 'hooks/usePrevious';
const useProvideSegment = () => {
const [location, setLocation] = useState();
const router = useRouter();
const referrer = usePrevious(location);
const identify = async (userId = null, traits = {}, options = {}) => {
const promise = new Promise((resolve) => {
window.analytics.identify(
userId,
traits,
merge(options, {
context: {
page: {
referrer,
},
},
}),
() => {
resolve();
},
);
});
return promise;
};
const group = (groupId = null, traits = {}, options = {}) => {
const promise = new Promise((resolve) => {
window.analytics.group(
groupId,
traits,
merge(options, {
context: {
page: {
referrer,
},
},
}),
() => {
resolve();
},
);
});
return promise;
};
const track = (event, properties = {}, options = {}) => {
window.analytics.track(
event,
properties,
merge(options, {
context: {
page: {
referrer,
},
},
}),
);
};
const page = () => {
window.analytics.page(
{
referrer,
},
{
context: {
page: {
referrer,
},
},
},
);
};
useEffect(() => {
setLocation(window.location.href);
if (location) {
page();
}
}, [router.asPath]);
return {
identify,
group,
track,
};
};
// create the context
const segmentContext = createContext();
// provide it to the tree
export const ProvideSegment = ({ children }) => {
const segment = useProvideSegment();
return (
<segmentContext.Provider value={segment}>
{children}
</segmentContext.Provider>
);
};
export const useSegment = () => useContext(segmentContext);
ProvideSegment.propTypes = {
children: PropTypes.node.isRequired,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment