1
1
import { debug , global } from './utils' ;
2
+ import delay from '../delay' ;
2
3
3
4
// After 30min no event we mark a session
4
5
const NEW_SESSION_TIME = 1000 * 60 * 30 ;
@@ -17,7 +18,24 @@ const markLastTimeEventSent = () => {
17
18
localStorage . setItem ( 'csb-last-event-sent' , Date . now ( ) . toString ( ) ) ;
18
19
} ;
19
20
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 ( ) ;
21
39
if ( typeof global . amplitude !== 'undefined' ) {
22
40
const identity = new global . amplitude . Identify ( ) ;
23
41
identity . set ( key , value ) ;
@@ -28,7 +46,8 @@ export const identify = (key: string, value: any) => {
28
46
}
29
47
} ;
30
48
31
- export const setUserId = ( userId : string ) => {
49
+ export const setUserId = async ( userId : string ) => {
50
+ await amplitudePromise ( ) ;
32
51
if ( typeof global . amplitude !== 'undefined' ) {
33
52
debug ( '[Amplitude] Setting User ID' , userId ) ;
34
53
identify ( 'userId' , userId ) ;
@@ -39,7 +58,8 @@ export const setUserId = (userId: string) => {
39
58
}
40
59
} ;
41
60
42
- export const resetUserId = ( ) => {
61
+ export const resetUserId = async ( ) => {
62
+ await amplitudePromise ( ) ;
43
63
if ( typeof global . amplitude !== 'undefined' ) {
44
64
debug ( '[Amplitude] Resetting User ID' ) ;
45
65
identify ( 'userId' , null ) ;
@@ -56,7 +76,8 @@ export const resetUserId = () => {
56
76
}
57
77
} ;
58
78
59
- export const track = ( eventName : string , data : any ) => {
79
+ export const track = async ( eventName : string , data : any ) => {
80
+ await amplitudePromise ( ) ;
60
81
if ( typeof global . amplitude !== 'undefined' ) {
61
82
const currentTime = Date . now ( ) ;
62
83
if ( currentTime - getLastTimeEventSent ( ) > NEW_SESSION_TIME ) {
0 commit comments