How do you detect when a MetaMask user disconnects their wallet from your dapp? I see there is a disconnect event
, but this is a for disconnecting from RPC - I want to know when the user has explicitly disconnected their wallet.
2 Answers
Use the accountschanged
event.
ethereum.on('accountsChanged', handler: (accounts: Array<string>) => void);
Verify if has any account.
ex: the accounts variable return an array, if has any account on array your dapp is conneted.
Use this code bellow:
const accounts = await ethereum.request({ method: "eth_accounts" });
const isConnected = !!accounts.length;