UNPKG

@scaleway/use-growthbook

Version:

Utility package to expose AB test tool

60 lines (59 loc) 1.58 kB
import { GrowthBook, GrowthBookProvider } from "@growthbook/growthbook-react"; import { useCallback, useEffect, useMemo } from "react"; import { jsx } from "react/jsx-runtime"; //#region src/AbTestProvider.tsx const defaultLoadConfig = { skipCache: false, timeout: 500 }; const getGrowthBookInstance = ({ config: { apiHost, clientKey, enableDevMode }, trackingCallback }) => new GrowthBook({ apiHost, clientKey, enableDevMode, trackingCallback }); const AbTestProvider = ({ children, config, trackingCallback, errorCallback, attributes, loadConfig }) => { const growthbook = useMemo(() => getGrowthBookInstance({ config, trackingCallback }), [trackingCallback, config]); const loadFeature = useCallback(async () => { if (config.clientKey) { const initConfig = { ...defaultLoadConfig, ...loadConfig }; await growthbook.init(initConfig); } }, [ growthbook, config, loadConfig ]); useEffect(() => { loadFeature().catch((error) => { if (errorCallback && error instanceof Error) errorCallback(error); return null; }); }, [loadFeature, errorCallback]); useEffect(() => { const currentAttributes = growthbook.getAttributes(); if (currentAttributes !== attributes) growthbook.setAttributes({ ...currentAttributes, ...attributes }).catch((error) => { if (errorCallback && error instanceof Error) errorCallback(error); return null; }); }, [ attributes, growthbook, errorCallback ]); return /* @__PURE__ */ jsx(GrowthBookProvider, { growthbook, children }); }; //#endregion export { AbTestProvider };