From d34d233cdec86e8fd312cc0061eadca4253fb2d7 Mon Sep 17 00:00:00 2001 From: Marcos Date: Tue, 6 Aug 2024 11:23:52 -0300 Subject: [PATCH] fix: Optimizely init fix --- src/data/optimizely.js | 7 ++++--- src/experiments/ExperimentsProvider.jsx | 7 +++++-- src/utils/optimizelyExperiment.js | 7 ++++++- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/data/optimizely.js b/src/data/optimizely.js index e0e9cbab..0acc1f02 100644 --- a/src/data/optimizely.js +++ b/src/data/optimizely.js @@ -10,16 +10,17 @@ ensureConfig([ * the OPTIMIZELY_FULL_STACK_SDK_KEY is available and will not be reinitialized afterward. Wrapping the initialization * in a function allows components to request the instance as-needed. */ +let instance = null; const getOptimizely = () => { const OPTIMIZELY_SDK_KEY = getConfig().OPTIMIZELY_FULL_STACK_SDK_KEY; - if (OPTIMIZELY_SDK_KEY) { - return createInstance({ + if (!instance && OPTIMIZELY_SDK_KEY) { + instance = createInstance({ sdkKey: OPTIMIZELY_SDK_KEY, }); } - return null; + return instance; }; const OPTIMIZELY_PROMPT_EXPERIMENT_KEY = '_cosmo__xpert_gpt_4_0_prompt'; diff --git a/src/experiments/ExperimentsProvider.jsx b/src/experiments/ExperimentsProvider.jsx index 9e3dfd87..b2bc70e2 100644 --- a/src/experiments/ExperimentsProvider.jsx +++ b/src/experiments/ExperimentsProvider.jsx @@ -9,15 +9,18 @@ const ExperimentsProvider = ({ children }) => { const { userId } = getAuthenticatedUser(); const optimizely = getOptimizely(); - return ( + return optimizely ? ( {children} + > + {children} + ) : ( + children ); }; diff --git a/src/utils/optimizelyExperiment.js b/src/utils/optimizelyExperiment.js index 68762b09..1ca3e241 100644 --- a/src/utils/optimizelyExperiment.js +++ b/src/utils/optimizelyExperiment.js @@ -2,7 +2,12 @@ import { getOptimizely } from '../data/optimizely'; const trackChatBotMessageOptimizely = (userId, userAttributes = {}) => { const optimizelyInstance = getOptimizely(); - optimizelyInstance.track('learning_assistant_chat_message', userId, userAttributes); + + if (!optimizelyInstance) { return; } + + optimizelyInstance.onReady().then(() => { + optimizelyInstance.track('learning_assistant_chat_message', userId, userAttributes); + }); }; export default trackChatBotMessageOptimizely;