Last active
December 1, 2019 08:52
-
-
Save bt4R9/7ffc1bdc6e89cc27c710965c9f63d197 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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