@scaleway/use-growthbook
Version:
Utility package to expose AB test tool
60 lines (59 loc) • 1.49 kB
JavaScript
import { jsx } from "react/jsx-runtime";
import { GrowthBook, GrowthBookProvider } from "@growthbook/growthbook-react";
import { useMemo, useCallback, useEffect } from "react";
const defaultLoadConfig = {
autoRefresh: false,
timeout: 500,
skipCache: false
};
const getGrowthBookInstance = ({
config: {
apiHost,
clientKey,
enableDevMode,
backgroundSync,
subscribeToChanges
},
trackingCallback
}) => new GrowthBook({
apiHost,
clientKey,
enableDevMode,
trackingCallback,
backgroundSync,
subscribeToChanges
});
const AbTestProvider = ({
children,
config,
trackingCallback,
errorCallback,
attributes,
loadConfig
}) => {
const growthbook = useMemo(
() => getGrowthBookInstance({ config, trackingCallback }),
[trackingCallback, config]
);
const loadFeature = useCallback(async () => {
if (config.clientKey) {
await growthbook.loadFeatures(loadConfig ?? defaultLoadConfig);
}
}, [growthbook, config, loadConfig]);
useEffect(() => {
loadFeature().catch(errorCallback);
}, [loadFeature, errorCallback]);
useEffect(() => {
const currentAttributes = growthbook.getAttributes();
if (currentAttributes !== attributes) {
growthbook.setAttributes({
...currentAttributes,
...attributes
}).catch(errorCallback);
}
}, [attributes, growthbook, errorCallback]);
return /* @__PURE__ */ jsx(GrowthBookProvider, { growthbook, children });
};
export {
AbTestProvider
};