diff --git a/src/client.ts b/src/client.ts index 522dc8f..858e4e3 100644 --- a/src/client.ts +++ b/src/client.ts @@ -361,6 +361,12 @@ class OptimizelyReactSDKClient implements ReactSDKClient { return null; } + if (this.userContext && areUsersEqual(userInfo, this.user)) { + // Important: We need to return the existing user context instance if the user info is the same + // new context misses the forced variation set on the existing context + return this.userContext; + } + return this._client.createUserContext(userInfo.id || undefined, userInfo.attributes); } diff --git a/src/utils.tsx b/src/utils.tsx index d17fce8..e824740 100644 --- a/src/utils.tsx +++ b/src/utils.tsx @@ -32,27 +32,18 @@ export function areUsersEqual(user1: UserInfo, user2: UserInfo): boolean { return false; } - const user1keys = Object.keys(user1.attributes || {}); - const user2keys = Object.keys(user2.attributes || {}); - user1keys.sort(); - user2keys.sort(); - const user1Attributes = user1.attributes || {}; const user2Attributes = user2.attributes || {}; - const areKeysLenEqual = user1keys.length === user2keys.length; - if (!areKeysLenEqual) { + const user1Keys = Object.keys(user1Attributes); + const user2Keys = Object.keys(user2Attributes); + + if (user1Keys.length !== user2Keys.length) { return false; } - for (let i = 0; i < user1keys.length; i++) { - const key1 = user1keys[i]; - const key2 = user2keys[i]; - if (key1 !== key2) { - return false; - } - - if (user1Attributes[key1] !== user2Attributes[key2]) { + for (const key of user1Keys) { + if (user1Attributes[key] !== user2Attributes[key]) { return false; } }