split-test-context.tsx 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { createContext, FC, useContext, useMemo } from 'react'
  2. import getMeta from '../../utils/meta'
  3. type SplitTestVariants = Record<string, any>
  4. type SplitTestInfo = Record<string, any>
  5. export const SplitTestContext = createContext<
  6. | {
  7. splitTestVariants: SplitTestVariants
  8. splitTestInfo: SplitTestInfo
  9. }
  10. | undefined
  11. >(undefined)
  12. export const SplitTestProvider: FC = ({ children }) => {
  13. const value = useMemo(
  14. () => ({
  15. splitTestVariants: getMeta('ol-splitTestVariants') || {},
  16. splitTestInfo: getMeta('ol-splitTestInfo') || {},
  17. }),
  18. []
  19. )
  20. return (
  21. <SplitTestContext.Provider value={value}>
  22. {children}
  23. </SplitTestContext.Provider>
  24. )
  25. }
  26. export function useSplitTestContext() {
  27. const context = useContext(SplitTestContext)
  28. if (!context) {
  29. throw new Error(
  30. 'useSplitTestContext is only available within SplitTestProvider'
  31. )
  32. }
  33. return context
  34. }
  35. export function useFeatureFlag(name: string) {
  36. const { splitTestVariants } = useSplitTestContext()
  37. return splitTestVariants[name] === 'enabled'
  38. }