From f782884579d9afefd077c14b8ce7663b09ee6f4a Mon Sep 17 00:00:00 2001 From: Bogdan Ivanov Date: Wed, 18 Sep 2024 21:54:17 +0300 Subject: [PATCH] fix: send events tracked before init --- packages/react/src/index.tsx | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx index e22dccb..b50a48b 100644 --- a/packages/react/src/index.tsx +++ b/packages/react/src/index.tsx @@ -1,6 +1,6 @@ 'use client'; -import { createContext, useContext, useEffect } from 'react'; +import { createContext, useContext, useEffect, useState } from 'react'; import { getApiUrl, inMemorySessionId, sendEvent, validateAppKey, type AptabaseOptions } from '../../shared'; // Session expires after 1 hour of inactivity @@ -10,10 +10,12 @@ const sdkVersion = `aptabase-react@${process.env.PKG_VERSION}`; let _appKey = ''; let _apiUrl: string | undefined; let _options: AptabaseOptions | undefined; +let _eventsBeforeInit: { [key: string]: Record | undefined } = {}; type ContextProps = { appKey?: string; options?: AptabaseOptions; + isInitialized: boolean; }; function init(appKey: string, options?: AptabaseOptions) { @@ -22,6 +24,11 @@ function init(appKey: string, options?: AptabaseOptions) { _apiUrl = options?.apiUrl ?? getApiUrl(appKey, options); _appKey = appKey; _options = options; + + Object.keys(_eventsBeforeInit).forEach((eventName) => { + trackEvent(eventName, _eventsBeforeInit[eventName]); + }); + _eventsBeforeInit = {}; } async function trackEvent(eventName: string, props?: Record): Promise { @@ -41,7 +48,12 @@ async function trackEvent(eventName: string, props?: Record({}); +function trackEventBeforeInit(eventName: string, props?: Record): Promise { + _eventsBeforeInit[eventName] = props; + return Promise.resolve(); +} + +const AptabaseContext = createContext({ isInitialized: false }); type Props = { appKey: string; @@ -56,11 +68,14 @@ export type AptabaseClient = { }; export function AptabaseProvider({ appKey, options, children }: Props) { + const [isInitialized, setIsInitialized] = useState(false); + useEffect(() => { init(appKey, options); + setIsInitialized(true); }, [appKey, options]); - return {children}; + return {children}; } export function useAptabase(): AptabaseClient { @@ -77,6 +92,12 @@ export function useAptabase(): AptabaseClient { }; } + if (!ctx.isInitialized) { + return { + trackEvent: trackEventBeforeInit, + }; + } + return { trackEvent, };