-
Notifications
You must be signed in to change notification settings - Fork 1
/
use-variant-id.tsx
35 lines (31 loc) · 1.15 KB
/
use-variant-id.tsx
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
import { useContext, useEffect } from 'react';
import { ExperimentAllocation } from './types';
import { CustomerIdContext } from '../../components/customer-id-context';
import { useSetExperimentAllocationMutation } from '../../graphql';
import { setExpGoogleAnalytics } from '../../utils/analytics';
export default function useVariantId(experiment: ExperimentAllocation) {
const customerId = useContext(CustomerIdContext) || 0;
const [setExperimentAllocation] = useSetExperimentAllocationMutation({
variables: {
customerId,
experimentId: experiment.experimentId,
variantId: experiment.variantId,
},
});
// Activate the experiment
useEffect(() => {
if (
customerId &&
customerId !== 0 &&
experiment.id === 0 &&
experiment.experimentId !== '0'
) {
// Save the experiment allocation in database
setExperimentAllocation();
}
// Set the experiment allocation in Google Analytics in order to tell
// Google Optimize which variant the visitor has seen
setExpGoogleAnalytics(`${experiment.experimentId}.${experiment.variantId}`);
}, [customerId]);
return experiment.variantId;
}