From 9f115f7866f49d5956a3463b2b9e45827d6a9c7f Mon Sep 17 00:00:00 2001 From: Emmanuella <113827536+ATella12@users.noreply.github.com> Date: Fri, 20 Dec 2024 20:33:30 +0100 Subject: [PATCH] using optional chaining (?.) in the getUserVariant function to simplify the logic and reduce the need for explicit null checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Problems/opportunities for improvement: The check for experimentClient being null or undefined is redundant, and the code can be cleaner using optional chaining. You also don't need the explicit if statement for experimentClient because the optional chaining operator will automatically handle it. Using Optional Chaining: Optional chaining allows you to access deeply nested properties without explicitly checking for null or undefined. If any part of the chain is null or undefined, the expression evaluates to undefined instead of throwing an error. What’s Changed: 1. Optional Chaining (?.): The line const variant = experimentClient?.variant(flagKey); uses optional chaining. This ensures that: If experimentClient is null or undefined, the code will safely return undefined instead of trying to call .variant(flagKey) and throwing an error. If experimentClient is valid, it proceeds to call variant(flagKey). 2. Simplified Logic: Since optional chaining handles the null/undefined check for you, you no longer need the explicit check for experimentClient. This reduces code clutter and makes it easier to maintain. 3. Error Handling: After getting the variant, we check if the variant exists. If it’s undefined (e.g., if the flag key doesn’t correspond to any variant), we log an error and return undefined. Thanks for reviewing this. --- libs/base-ui/contexts/Experiments.tsx | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/libs/base-ui/contexts/Experiments.tsx b/libs/base-ui/contexts/Experiments.tsx index 313a813da8..e020235bf2 100644 --- a/libs/base-ui/contexts/Experiments.tsx +++ b/libs/base-ui/contexts/Experiments.tsx @@ -75,16 +75,17 @@ export default function ExperimentsProvider({ children }: ExperimentsProviderPro if (!isReady) { return undefined; } - if (!experimentClient) { - console.error('No experiment clients found'); - return undefined; + const variant = experimentClient?.variant(flagKey); + + if (!variant) { + console.error('Variant not found for flag key:', flagKey); + return undefined; } - const variant = experimentClient.variant(flagKey); + return variant.value; }, [isReady, experimentClient], ); - const values = useMemo(() => { return { experimentClient, isReady, getUserVariant }; }, [isReady, getUserVariant]);