Skip to content

Commit 752724c

Browse files
authored
Amplitude first messages (codesandbox#3166)
* Allow first messages to be sent to amplitude * Only send after amplitude is initialized
1 parent a4bce4f commit 752724c

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

packages/common/src/utils/analytics/amplitude.ts

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { debug, global } from './utils';
2+
import delay from '../delay';
23

34
// After 30min no event we mark a session
45
const NEW_SESSION_TIME = 1000 * 60 * 30;
@@ -17,7 +18,24 @@ const markLastTimeEventSent = () => {
1718
localStorage.setItem('csb-last-event-sent', Date.now().toString());
1819
};
1920

20-
export const identify = (key: string, value: any) => {
21+
const amplitudePromise = async () => {
22+
for (let i = 0; i < 10; i++) {
23+
if (
24+
typeof global.amplitude !== 'undefined' &&
25+
global.amplitude.getInstance()._storageSuffix
26+
) {
27+
return true;
28+
}
29+
30+
// eslint-disable-next-line no-await-in-loop
31+
await delay(1000);
32+
}
33+
34+
return false;
35+
};
36+
37+
export const identify = async (key: string, value: any) => {
38+
await amplitudePromise();
2139
if (typeof global.amplitude !== 'undefined') {
2240
const identity = new global.amplitude.Identify();
2341
identity.set(key, value);
@@ -28,7 +46,8 @@ export const identify = (key: string, value: any) => {
2846
}
2947
};
3048

31-
export const setUserId = (userId: string) => {
49+
export const setUserId = async (userId: string) => {
50+
await amplitudePromise();
3251
if (typeof global.amplitude !== 'undefined') {
3352
debug('[Amplitude] Setting User ID', userId);
3453
identify('userId', userId);
@@ -39,7 +58,8 @@ export const setUserId = (userId: string) => {
3958
}
4059
};
4160

42-
export const resetUserId = () => {
61+
export const resetUserId = async () => {
62+
await amplitudePromise();
4363
if (typeof global.amplitude !== 'undefined') {
4464
debug('[Amplitude] Resetting User ID');
4565
identify('userId', null);
@@ -56,7 +76,8 @@ export const resetUserId = () => {
5676
}
5777
};
5878

59-
export const track = (eventName: string, data: any) => {
79+
export const track = async (eventName: string, data: any) => {
80+
await amplitudePromise();
6081
if (typeof global.amplitude !== 'undefined') {
6182
const currentTime = Date.now();
6283
if (currentTime - getLastTimeEventSent() > NEW_SESSION_TIME) {

0 commit comments

Comments
 (0)