Know when MetaMask wallet has switched

is there a way to call a function when the user switches there metamask wallet to another wallet.

Im trying to achieve the same thing as 1Inch where if you switch wallets the data on the page is automatically reloaded.

I have found this in the Moralis documentation

Moralis.onAccountsChanged(async function (accounts) {



But this function is only called if the user disconnects or connects their wallet and is not called on a simple switch.

You mean that this doesn’t work for you?

Moralis.onAccountsChanged(function(accounts) {

    console.log("x", accounts);
// your code to run when "accountsChanged" happens


For me I get that console.log output every time I change an account in MetaMask.

Just retested it and it does work when you switch accounts.

The problem i’m having is when i use this code to get the nativeBalance

const balance = await Moralis.Web3API.account.getNativeBalance(options)

It returns the native balance of the previously connect wallet as opposed to the one which the user just switched too.

1 Like

Currently Web3API takes ethAddress from user object.
If you want to work with Moralis.onAccountsChanged without linking address to account you can get addresses dynamically:

const web3 = await Moralis.enable();
const address = (await web3.eth.getAccounts())[0];