All files / app experimentation.ts

0% Statements 0/11
0% Branches 0/5
0% Functions 0/4
0% Lines 0/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42                                                                                   
import { GrowthBook } from "@growthbook/growthbook";
import { GrowthBookContext } from "@growthbook/growthbook-react";
import { useContext } from "react";
 
// Flags are evaluated locally by the GrowthBook SDK (see features/experimentation/WithFlags.tsx).
// We read the context directly rather than via GrowthBook's hooks so these work on pages not wrapped
// in <WithFlags> too - there growthbook is undefined and the in-code default is returned. Always
// pass a default; it's also what's returned before flags finish loading.
 
export type JsonValue =
  | boolean
  | number
  | string
  | null
  | JsonValue[]
  | { [key: string]: JsonValue };
 
export function shouldPassAllGates(): boolean {
  return process.env.NEXT_PUBLIC_EXPERIMENTATION_PASS_ALL_GATES === "1";
}
 
function useGrowthBookOrUndefined(): GrowthBook | undefined {
  return useContext(GrowthBookContext).growthbook as GrowthBook | undefined;
}
 
export function useGate(gateName: string): boolean {
  const growthbook = useGrowthBookOrUndefined();
  return shouldPassAllGates() || (growthbook?.isOn(gateName) ?? false);
}
 
export function useFeatureValue<T extends JsonValue>(
  featureName: string,
  defaultValue: T,
): T {
  const growthbook = useGrowthBookOrUndefined();
  return (
    growthbook
      ? growthbook.getFeatureValue(featureName, defaultValue)
      : defaultValue
  ) as T;
}