From 31a27b256646ed50bc7aa35a752d0a676f2ff761 Mon Sep 17 00:00:00 2001 From: Aswathy-Deriv <96725617+aswathy-deriv@users.noreply.github.com> Date: Wed, 4 Sep 2024 11:59:58 +0530 Subject: [PATCH] feat: Add cache events (#109) * fix: added cache events in the analytics ready function * fix: peer comments --- src/rudderstack.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/rudderstack.ts b/src/rudderstack.ts index 536d145..1547f4d 100644 --- a/src/rudderstack.ts +++ b/src/rudderstack.ts @@ -2,6 +2,12 @@ import { RudderAnalytics } from '@rudderstack/analytics-js' import { TCoreAttributes, TEvents } from './types' import { v6 as uuidv6 } from 'uuid' +interface AnalyticsEvent { + name: string + properties: { + [key: string]: string + } +} export class RudderStack { analytics = new RudderAnalytics() has_identified = false @@ -42,11 +48,34 @@ export class RudderStack { */ getUserId = () => this.analytics.getUserId() + /** For caching mechanism, Rudderstack SDK, first page load */ + handleCachedEvents = () => { + const storedEvents = localStorage.getItem('cached_analytics_events') + try { + if (storedEvents) { + let eventQueue: AnalyticsEvent[] = JSON.parse(storedEvents) as AnalyticsEvent[] + + if (eventQueue.length > 0) { + eventQueue.forEach(event => { + this.analytics.track(event.name, event.properties) + }) + + eventQueue = [] + localStorage.removeItem('cached_analytics_events') + } + } + } catch (error) { + // eslint-disable-next-line no-console + console.log(error) + } + } + /** * Initializes the Rudderstack SDK. Ensure that the appropriate environment variables are set before this is called. * For local/staging environment, ensure that `RUDDERSTACK_STAGING_KEY` and `RUDDERSTACK_URL` is set. * For production environment, ensure that `RUDDERSTACK_PRODUCTION_KEY` and `RUDDERSTACK_URL` is set. */ + init = (RUDDERSTACK_KEY: string) => { if (RUDDERSTACK_KEY) { this.setCookieIfNotExists() @@ -56,6 +85,7 @@ export class RudderStack { this.analytics.ready(() => { this.has_initialized = true this.has_identified = !!(this.getUserId() || this.getAnonymousId()) + this.handleCachedEvents() }) } }