split-test-context.tsx 1.3 KB

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