Skip to content

Instantly share code, notes, and snippets.

@bt4R9
Last active December 1, 2019 08:52
Show Gist options
  • Save bt4R9/7ffc1bdc6e89cc27c710965c9f63d197 to your computer and use it in GitHub Desktop.
Save bt4R9/7ffc1bdc6e89cc27c710965c9f63d197 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect, useContext, useMemo } from "react";
import Experiments, { ExperimentsBag } from "@wix/wix-experiments";
export interface ExperimentsProvider {
options: {
experiments?: ExperimentsBag;
scope?: string;
baseUrl?: string;
};
}
const ExperimentsContext = React.createContext<Experiments | Promise<void>>(
null as any
);
export const ExperimentsProvider: React.FC<React.PropsWithChildren<
ExperimentsProvider
>> = ({ children, options = {} }) => {
const experimentsInstance = useMemo(() => new Experiments(options), [
options.experiments,
options.scope,
options.baseUrl
]);
const promise = useMemo(() => experimentsInstance.ready(), [
experimentsInstance
]);
const [ready, setReady] = useState(!experimentsInstance.pending());
useEffect(() => {
let unmounted = false;
if (!ready) {
promise
.then(() => {
if (!unmounted) {
setReady(true);
}
})
.catch(() => {});
}
() => (unmounted = true);
});
return (
<ExperimentsContext.Provider value={ready ? experimentsInstance : promise}>
{children}
</ExperimentsContext.Provider>
);
};
export const useExperiments = () => {
const value = useContext(ExperimentsContext);
if (typeof (value as Promise<void>).then === "function") {
throw value as Promise<void>;
}
return value as Experiments;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment