From 75c39f303bc24f71c2092d5c1edb8844b2fbae3a Mon Sep 17 00:00:00 2001 From: Jamey H Date: Mon, 11 Sep 2023 10:25:45 -0400 Subject: [PATCH] fix(app): ensure mixpanel initialization before opting out of tracking (#13508) Fixes a redux store crash issue caused by opting out of analytics tracking before the mixpanel object is properly initialized. --- app/src/redux/analytics/mixpanel.ts | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/app/src/redux/analytics/mixpanel.ts b/app/src/redux/analytics/mixpanel.ts index ce60e8be24e..d29d9c0c362 100644 --- a/app/src/redux/analytics/mixpanel.ts +++ b/app/src/redux/analytics/mixpanel.ts @@ -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 { @@ -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) @@ -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) } } }