split-test-context.tsx 932 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. }