Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: AB testing system #1013

Merged
merged 7 commits into from
Nov 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/services/analytics/gtm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import {
} from '@/config/constants'
import type { AnalyticsEvent, EventLabel, SafeAppEvent } from './types'
import { EventType } from './types'
import { getAbTest } from '../tracking/abTesting'
import type { AbTest } from '../tracking/abTesting'

type GTMEnvironment = 'LIVE' | 'LATEST' | 'DEVELOPMENT'
type GTMEnvironmentArgs = Required<Pick<TagManagerArgs, 'auth' | 'preview'>>
Expand Down Expand Up @@ -85,6 +87,7 @@ export const gtmClear = (): void => {
type GtmEvent = {
event: EventType
chainId: string
abTest?: AbTest
}

type ActionGtmEvent = GtmEvent & {
Expand Down Expand Up @@ -118,6 +121,12 @@ export const gtmTrack = (eventData: AnalyticsEvent): void => {
gtmEvent.eventLabel = eventData.label
}

const abTest = getAbTest()

if (abTest) {
gtmEvent.abTest = abTest
}

gtmSend(gtmEvent)
}

Expand Down
11 changes: 11 additions & 0 deletions src/services/tracking/abTesting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const enum AbTest {}

let _abTest: AbTest | null = null

export const setAbTest = (abTest: AbTest): void => {
_abTest = abTest
}

export const getAbTest = (): AbTest | null => {
return _abTest
}
30 changes: 30 additions & 0 deletions src/services/tracking/useABTesting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useEffect, useMemo } from 'react'

import useLocalStorage from '@/services/local-storage/useLocalStorage'
import { setAbTest } from './abTesting'
import type { AbTest } from './abTesting'

const useABTesting = (abTest: AbTest): boolean => {
// Fallback AB test value if no `localStorage` exists
const coinToss = useMemo(() => {
return Math.random() >= 0.5
}, [])

const [isB = coinToss, setIsB] = useLocalStorage<boolean>(`AB_${abTest}`)

// Save fallback value to `localStorage` if no cache exists
useEffect(() => {
setIsB((prev) => prev ?? coinToss)
}, [coinToss, isB, setIsB])

// Store AB test value in GTM
useEffect(() => {
if (isB) {
setAbTest(abTest)
}
}, [abTest, isB])

return isB
}

export default useABTesting