Skip to content

Commit

Permalink
feat: Add cache events (#109)
Browse files Browse the repository at this point in the history
* fix: added cache events in the analytics ready function

* fix: peer comments
  • Loading branch information
aswathy-deriv authored Sep 4, 2024
1 parent 00f35dc commit 31a27b2
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/rudderstack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -56,6 +85,7 @@ export class RudderStack {
this.analytics.ready(() => {
this.has_initialized = true
this.has_identified = !!(this.getUserId() || this.getAnonymousId())
this.handleCachedEvents()
})
}
}
Expand Down

0 comments on commit 31a27b2

Please sign in to comment.