Skip to content

Commit

Permalink
feat: simpler approach -> pending events queue
Browse files Browse the repository at this point in the history
  • Loading branch information
roshaans committed Jul 13, 2023
1 parent e93df49 commit 0075fc2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 14 deletions.
12 changes: 1 addition & 11 deletions src/hooks/usePageAnalytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,6 @@ export function usePageAnalytics() {
const { asPath } = router;
useEffect(() => {
const justPath = asPath.split('?')[0];
// 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);
}
recordPageView(justPath);
}, [asPath]);
}
14 changes: 11 additions & 3 deletions src/utils/rudder-analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ let rudderAnalytics: Analytics | null = null;
let anonymousUserId = '';
let hashId = '';
let anonymousUserIdCreatedAt = '';
let pendingEvents: any = [];

declare global {
interface Window {
rudderanalytics: Analytics | undefined;
analyticsInitialized: boolean;
}
}

Expand Down Expand Up @@ -63,7 +63,10 @@ export async function init() {
window.rudderanalytics.load(rudderAnalyticsKey, analyticsUrl);
rudderAnalytics = window.rudderanalytics;
if (rudderAnalytics) rudderAnalytics.setAnonymousId(getAnonymousId());
window.analyticsInitialized = true;
for (const event of pendingEvents) {
event();
}
pendingEvents = [];
} catch (e) {
console.error(e);
}
Expand All @@ -80,7 +83,12 @@ function filterURL(url: string) {
}

export function recordPageView(pageName: string) {
if (!rudderAnalytics) return;
if (!rudderAnalytics) {
pendingEvents.push(() => {
recordPageView(pageName)
})
return;
}
try {
rudderAnalytics.page('category', pageName, {
hashId: localStorage.getItem('hashId'),
Expand Down

0 comments on commit 0075fc2

Please sign in to comment.