25
loading...
This website collects cookies to deliver better user experience
// Set a random number between 0 and 1 based on session id
const randomFromSession = randomFromSeed(req.sessionID);
// Set it when creating our Redux store
const defaultStoreState = { ab: { cohortId: randomFromSession } };
const store = createStore(
reducers,
defaultStoreState,
applyMiddleware(thunk)
);
// Send back a cookie with the cohort ID to the client in the response
res.cookie('cohortId', `${randomFromSession}`, {
maxAge: 86400000,
httpOnly: false
});
import { Experiment, Variant } from './components/ABTesting';
import { experiments } from './config/abExperiments';
class ComponentWithExperiment extends React.Component {
render() {
<Experiment experimentId={experiments.testExperiment}>
<Variant>Variant 1</Variant>
<Variant>Variant 2</Variant>
</Experiment>
}
}
Experiment
component, and nest our variants in Variant
, just for clarity. The Variant
component is just rendering its children, it is only there for code readability.constructor(props) {
super(props);
// Set cohort on server and client
let cohortId = 0;
let cohortSet = false;
if (
props.cohortId !== undefined &&
props.cohortId !== null &&
typeof props.cohortId === 'number' &&
Number.isFinite(props.cohortId) &&
props.cohortId >= 0 &&
props.cohortId < 1
) {
cohortId = props.cohortId;
cohortSet = true;
}
this.state = {
cohortId,
cohortSet
};
}
componentDidMount() {
const variantChildren = React.Children.toArray(this.props.children);
const numberOfVariants = variantChildren.length;
const { experimentId } = this.props;
// Set cohort on client
if (!this.state.cohortSet) {
const cohortIdFromCookie = cookie.get('cohortId');
const cohortId = cohortIdFromCookie === null ? 0 : cohortIdFromCookie;
this.setState({ cohortId: cohortId, cohortSet: true });
this.props.abActions.updateCohortId({ cohortId });
this.setExperimentCookie(
experimentId,
this.getVariantId(cohortId, numberOfVariants)
);
} else {
this.setExperimentCookie(
experimentId,
this.getVariantId(this.props.cohortId, numberOfVariants)
);
}
}
componentDidMount
only will be called on the client.getVariantId
is just a function returning a 0-indexed number based on the number of variants and the cohort-id. You can check it out in the full file linked above.gaProperty
variable along.gaProperty
variable as expId
and expVar
under Fields to Set in the variable settings. Sending these along with the pageview makes Google Analytics aware of any experiments running for a user in a particular session. You can then track your variant’s progress in Optimize.