narrow-lifeguard-42299
05/07/2025, 10:13 PMnarrow-lifeguard-42299
05/07/2025, 10:15 PMimport {
StickyAssignmentsDocument,
StickyBucketService
} from '@growthbook/growthbook';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { reportError } from 'utils';
export class GrowthBookStickyBucketService extends StickyBucketService {
constructor(opts?: { prefix?: string }) {
super(opts);
// If you want to override the prefix from the parent class:
this.prefix = opts?.prefix || 'growthbook_stickyBucketing_';
}
// gets assigned variation for a user in an experiment
async getAssignments(attributeName: string, attributeValue: string) {
try {
const key = this.getKey(attributeName, attributeValue);
const value = await AsyncStorage.getItem(key);
if (!value) return null;
return JSON.parse(value);
} catch (error) {
reportError(
`Failed to retrieve sticky bucket assignment with error: ${error as Error}`
);
return null;
}
}
// saves assigned variation for a user in an experiment
async saveAssignments(doc: StickyAssignmentsDocument) {
try {
const key = this.getKey(doc.attributeName, doc.attributeValue);
await AsyncStorage.setItem(key, JSON.stringify(doc));
return true;
} catch (error) {
reportError(
`Failed to save sticky bucket assignment with error: ${error as Error}`
);
return false;
}
}
// helper method to generate a consistent storage key
getKey(attributeName: string, attributeValue: string) {
return `${this.prefix}${attributeName}||${attributeValue}`;
}
}
and in our growthbook instance:
export const growthbook = new GrowthBook({
// other initialisation data
stickyBucketService: new GrowthBookStickyBucketService(),
});