mixpanel / mixpanel-js

Official Mixpanel JavaScript Client Library
https://mixpanel.com/help/reference/javascript
Other
888 stars 312 forks source link

`track_links` does not work in a React app unless wrapped in a `useEffect` + `setTimeout` #419

Open nicolassanmar opened 9 months ago

nicolassanmar commented 9 months ago

Hey, I want to track some links that lead to external websites using the mixpanel.track_links method. Unfortunately this causes the app to break unless mixpanel.track_links is called within a useEffect (which makes sense) and a setTimeout (which I don't understand).

I want to track the links this way (not using track and using onClick to redirect) because I also want to use the Next.js feature that allows you to prefetch links.

I created a minimal repo reproducing this issue here: https://github.com/nicolassanmar/mixpanel-track-links-next-reproduction It throws errors when you call track_links using either a ref or the element's id if you don't call it using a timeout:

image

I don't think this is related to the initialization of Mixpanel, since in the reproduction I initialize Mixpanel and then navigate to the page that does not use a setTimeout and it fails

The same issue can be replicated with mixpanel.track_forms