Created
October 17, 2021 00:11
-
-
Save lukebussey/d2a5d4a71bbbbb26fa2e05c43773be97 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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