From e4610e467232b822a7c58a060c4e26d86c445e5c Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Wed, 26 Apr 2023 09:03:35 +0100 Subject: [PATCH] Posthog properly handle Analytics ID changing from under us (#10702) * Posthog properly handle Analytics ID changing from under us * Update tests --- src/PosthogAnalytics.ts | 8 ++++++++ test/PosthogAnalytics-test.ts | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/src/PosthogAnalytics.ts b/src/PosthogAnalytics.ts index 5c5805af93..2a7e24294e 100644 --- a/src/PosthogAnalytics.ts +++ b/src/PosthogAnalytics.ts @@ -312,6 +312,14 @@ export class PosthogAnalytics { Object.assign({ id: analyticsID }, accountData), ); } + if (this.posthog.get_distinct_id() === analyticsID) { + // No point identifying again + return; + } + if (this.posthog.persistence.get_user_state() === "identified") { + // Analytics ID has changed, reset as Posthog will refuse to merge in this case + this.posthog.reset(); + } this.posthog.identify(analyticsID); } catch (e) { // The above could fail due to network requests, but not essential to starting the application, diff --git a/test/PosthogAnalytics-test.ts b/test/PosthogAnalytics-test.ts index 61a46a5405..21d0d7cf0f 100644 --- a/test/PosthogAnalytics-test.ts +++ b/test/PosthogAnalytics-test.ts @@ -33,6 +33,10 @@ const getFakePosthog = (): PostHog => identify: jest.fn(), reset: jest.fn(), register: jest.fn(), + get_distinct_id: jest.fn(), + persistence: { + get_user_state: jest.fn(), + }, } as unknown as PostHog); interface ITestEvent extends IPosthogEvent {