Skip to content

Commit

Permalink
fix(app): ensure mixpanel initialization before opting out of tracking (
Browse files Browse the repository at this point in the history
#13508)

Fixes a redux store crash issue caused by opting out of analytics tracking before the mixpanel object is properly initialized.
  • Loading branch information
mjhuff authored and jerader committed Sep 12, 2023
1 parent c5d4646 commit 75c39f3
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions app/src/redux/analytics/mixpanel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@ const MIXPANEL_OPTS = {
track_pageview: false,
}

const initMixpanelInstanceOnce = initializeMixpanelInstanceOnce(MIXPANEL_ID)

export function initializeMixpanel(
config: AnalyticsConfig,
isOnDevice: boolean | null
): void {
if (MIXPANEL_ID) {
log.debug('Initializing Mixpanel', { config })

mixpanel.init(MIXPANEL_ID, MIXPANEL_OPTS)
initMixpanelInstanceOnce(config)
setMixpanelTracking(config, isOnDevice)
trackEvent({ name: 'appOpen', properties: {} }, config)
} else {
Expand All @@ -54,6 +54,7 @@ export function setMixpanelTracking(
isOnDevice: boolean | null
): void {
if (MIXPANEL_ID) {
initMixpanelInstanceOnce(config)
if (config.optedIn) {
log.debug('User has opted into analytics; tracking with Mixpanel')
mixpanel.identify(config.appId)
Expand All @@ -65,11 +66,22 @@ export function setMixpanelTracking(
})
} else {
log.debug('User has opted out of analytics; stopping tracking')
const config = mixpanel?.get_config?.()
if (config != null) {
mixpanel.opt_out_tracking?.()
mixpanel.reset?.()
}
mixpanel.opt_out_tracking?.()
mixpanel.reset?.()
}
}
}

function initializeMixpanelInstanceOnce(
MIXPANEL_ID?: string
): (config: AnalyticsConfig) => undefined {
let hasBeenInitialized = false

return function (config: AnalyticsConfig): undefined {
if (!hasBeenInitialized && MIXPANEL_ID) {
hasBeenInitialized = true
log.debug('Initializing Mixpanel', { config })
return mixpanel.init(MIXPANEL_ID, MIXPANEL_OPTS)
}
}
}

0 comments on commit 75c39f3

Please sign in to comment.