I am trying to implement Mixpanel with my React App using Google Tag Manager. I have successfully integrated it using GTM but I have trouble with mixpanel always being undefined on reload. I am using CDN for it.
If I go onto some other page and come back to the page where I am using Mixpanel, there's no error. So I diagnosed that as it is an asynchronous operation it takes some time to load mixpanel in my app. So I tried using the useEffect hook and useState but it failed to solve my problem.
Below is my code:
const [mixpanelLoad, setMixpanelLoad] = useState(false);
useEffect(()=>{
console.log('IN USEEFFECT');
console.log(mixpanel);
if (mixpanel) {
// It never comes here on first reload
setMixpanelLoad(true);
console.log('MIXPANEL LOADED');
}
if (mixpanelLoad) {
// thus it never does the tracking
console.log('DOING TRACKING');
mixpanel.track('Track Bill Page');
}
}, [mixpanelLoad]);
On first reload it always says that mixpanel is undefined.
I am using CDN so I don't have to use any mixpanel library.
Certain methods/features can only be used after the Mixpanel library has finished loading. init() has a loaded function available to handle this automatically -
mixpanel.init('YOUR PROJECT TOKEN', {
loaded: function(mixpanel) {
distinct_id = mixpanel.get_distinct_id();
}
});