React Example
This page shows how easily EmbedUI can be added to React App with the help of React Context Provider
import React, {
createContext,
useContext,
ReactNode,
useEffect,
useState,
} from 'react';
declare global {
interface Window {
EmbedUI: any;
}
}
type TsetAliasEvent = {
// Here publicKey denotes user's wallet publicKey
publicKey: string;
};
interface IQwestiveEmbedUIContext {
isLoading: boolean;
setAlias?: ({ publicKey }: TsetAliasEvent) => void;
openPopup?: () => void;
closePopup?: () => void;
logout?: () => void;
}
const SDKContext = createContext<IQwestiveEmbedUIContext | null>(null);
/*
Note: Please update below variables with actual values that are
available in your project settings page
API KEY refers to the public api key that needs to be used from
the client-side code and please try to avoid using the secret api
key from the project settings, which is supposed to be used server-side only.
*/
const QWESTIVE_REFERRAL_PROJECT_ID = "YOUR_PROJECT_ID";
const QWESTIVE_REFERRAL_API_KEY = "YOUR_API_KEY";
function useQwestiveEmbedUIProvider(): IQwestiveEmbedUIContext {
const [qwestiveMethods, setQwestiveMethods] =
useState<IQwestiveEmbedUIContext>({
isLoading: true,
});
useEffect(() => {
if (window.EmbedUI.isInitialized) return;
const loadEmbedUIMethods = () => {
try {
const apiMethods = window?.EmbedUI?.init({
apiKey: QWESTIVE_REFERRAL_API_KEY,
projectId: QWESTIVE_REFERRAL_PROJECT_ID,
});
setQwestiveMethods({ ...apiMethods, isLoading: false });
window.EmbedUI.isInitialized = true;
} catch (e) {
console.error(
'Error occurred while loading QwestiveEmbedUI API methods',
);
setQwestiveMethods({ isLoading: false });
}
};
window?.EmbedUI?.loadEmbedUI(() => {
loadEmbedUIMethods();
});
}, []);
return {
isLoading: qwestiveMethods?.isLoading,
setAlias: ({ publicKey }: { publicKey: string }) =>
qwestiveMethods?.setAlias?.({ publicKey }),
openPopup: qwestiveMethods?.openPopup,
closePopup: qwestiveMethods?.closePopup,
logout: qwestiveMethods?.logout,
};
}
export function QwestiveEmbedUIContextProvider({
children,
}: {
children: ReactNode;
}): JSX.Element {
const scriptContext = useQwestiveEmbedUIProvider();
return (
<SDKContext.Provider value={scriptContext}>{children}</SDKContext.Provider>
);
}
export function useEmbedUISDK(): IQwestiveEmbedUIContext {
const context = useContext(SDKContext);
if (!context)
throw new Error(
'useEmbedUISDK must be called from within the corresponding ContextProvider'
);
return context;
}
Last updated