UNPKG

@web3auth/no-modal

Version:
71 lines (68 loc) 2.56 kB
import { useContext, useState, useEffect, useMemo, createElement, createContext } from 'react'; import { EVM_PLUGINS, PLUGIN_EVENTS } from '../../base/plugin/IPlugin.js'; import { CONNECTOR_STATUS } from '../../base/connector/constants.js'; const WalletServicesContext = createContext(null); function WalletServicesContextProvider({ children, context }) { const web3AuthContext = useContext(context); const { getPlugin, isInitialized, isConnected } = web3AuthContext; const [ready, setReady] = useState(false); const [connecting, setConnecting] = useState(false); const [walletServicesPlugin, setWalletServicesPlugin] = useState(null); useEffect(() => { if (isInitialized) { const plugin = getPlugin(EVM_PLUGINS.WALLET_SERVICES); setWalletServicesPlugin(plugin); } }, [isInitialized, getPlugin]); useEffect(() => { if (isConnected) { const plugin = getPlugin(EVM_PLUGINS.WALLET_SERVICES); setWalletServicesPlugin(plugin); // when rehydrating, the connectedListener may be registered after the connected event is emitted, we need to check the status here if ((plugin === null || plugin === void 0 ? void 0 : plugin.status) === CONNECTOR_STATUS.CONNECTED) setReady(true); } }, [isConnected, getPlugin, walletServicesPlugin]); useEffect(() => { const connectedListener = () => { setReady(true); setConnecting(false); }; const disconnectedListener = () => { setReady(false); setConnecting(false); }; const connectingListener = () => { setConnecting(true); }; if (walletServicesPlugin) { walletServicesPlugin.on(PLUGIN_EVENTS.CONNECTED, connectedListener); walletServicesPlugin.on(PLUGIN_EVENTS.DISCONNECTED, disconnectedListener); walletServicesPlugin.on(PLUGIN_EVENTS.CONNECTING, connectingListener); } return () => { if (walletServicesPlugin) { walletServicesPlugin.removeListener(PLUGIN_EVENTS.CONNECTED, connectedListener); walletServicesPlugin.removeListener(PLUGIN_EVENTS.DISCONNECTED, disconnectedListener); walletServicesPlugin.removeListener(PLUGIN_EVENTS.CONNECTING, connectingListener); } }; }, [walletServicesPlugin]); const value = useMemo(() => { return { plugin: walletServicesPlugin, ready, connecting }; }, [walletServicesPlugin, ready, connecting]); return createElement(WalletServicesContext.Provider, { value }, children); } export { WalletServicesContext, WalletServicesContextProvider };