@web3auth/no-modal
Version:
Multi chain wallet aggregator for web3Auth
60 lines (57 loc) • 2.17 kB
JavaScript
import { useState, useEffect, useMemo } from 'react';
import { EVM_PLUGINS, PLUGIN_EVENTS } from '../../base/plugin/IPlugin.js';
import { CONNECTED_STATUSES } from '../../base/connector/connectorStatus.js';
function useWalletServicesContextValue(web3AuthContext) {
const {
getPlugin,
isInitialized,
isConnected
} = web3AuthContext;
const [ready, setReady] = useState(false);
const [connecting, setConnecting] = useState(false);
const [walletServicesPlugin, setWalletServicesPlugin] = useState(null);
useEffect(() => {
if (!isInitialized) return;
const plugin = getPlugin(EVM_PLUGINS.WALLET_SERVICES);
setWalletServicesPlugin(plugin);
}, [isInitialized, getPlugin]);
useEffect(() => {
if (!isConnected) return;
const plugin = getPlugin(EVM_PLUGINS.WALLET_SERVICES);
setWalletServicesPlugin(plugin);
// When rehydrating, the connected listener may be registered after the connected event is emitted.
if (CONNECTED_STATUSES.includes(plugin === null || plugin === void 0 ? void 0 : plugin.status)) setReady(true);
}, [isConnected, getPlugin]);
useEffect(() => {
const plugin = walletServicesPlugin;
if (!plugin) return undefined;
const connectedListener = () => {
setReady(true);
setConnecting(false);
};
const disconnectedListener = () => {
setReady(false);
setConnecting(false);
};
const connectingListener = () => {
setConnecting(true);
};
plugin.on(PLUGIN_EVENTS.CONNECTED, connectedListener);
plugin.on(PLUGIN_EVENTS.DISCONNECTED, disconnectedListener);
plugin.on(PLUGIN_EVENTS.CONNECTING, connectingListener);
return () => {
if (!plugin) return;
plugin.removeListener(PLUGIN_EVENTS.CONNECTED, connectedListener);
plugin.removeListener(PLUGIN_EVENTS.DISCONNECTED, disconnectedListener);
plugin.removeListener(PLUGIN_EVENTS.CONNECTING, connectingListener);
};
}, [walletServicesPlugin]);
return useMemo(() => {
return {
plugin: walletServicesPlugin,
ready,
connecting
};
}, [walletServicesPlugin, ready, connecting]);
}
export { useWalletServicesContextValue };