Skip to content

Commit

Permalink
fix: wait for rudderstack to load before sending initial page event
Browse files Browse the repository at this point in the history
  • Loading branch information
roshaans committed Jul 13, 2023
1 parent 0562226 commit e93df49
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/hooks/usePageAnalytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ export function usePageAnalytics() {
const { asPath } = router;
useEffect(() => {
const justPath = asPath.split('?')[0];
recordPageView(justPath);
// wait for analytics library to initilize on initial page load before sending event
if (window.analyticsInitialized) {
recordPageView(justPath);
} else {
const checkInterval = setInterval(() => {
if (window.analyticsInitialized) {
recordPageView(justPath);
clearInterval(checkInterval);
}
}, 100);
}
}, [asPath]);
}
2 changes: 2 additions & 0 deletions src/utils/rudder-analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ let anonymousUserIdCreatedAt = '';
declare global {
interface Window {
rudderanalytics: Analytics | undefined;
analyticsInitialized: boolean;
}
}

Expand Down Expand Up @@ -62,6 +63,7 @@ export async function init() {
window.rudderanalytics.load(rudderAnalyticsKey, analyticsUrl);
rudderAnalytics = window.rudderanalytics;
if (rudderAnalytics) rudderAnalytics.setAnonymousId(getAnonymousId());
window.analyticsInitialized = true;
} catch (e) {
console.error(e);
}
Expand Down

0 comments on commit e93df49

Please sign in to comment.