How to detect when the connected wallet changes selected account web3 JS

In this tutorial, we are going to learn how to detect when the wallet connected to your website changes the selected account with Web3 JS

In this tutorial, we are going to learn how to detect when the wallet connected to your website changes the selected account with Web3 JS.

This is useful for 2 reasons:

  1. it allows you to always have the right account in a variable so you don't need to get the selected account every time you want to do something
  2. it allows you to update your UI according to the selected account. For example if you display the connected account, you will be able to update that when the user changes the selected account

Now, the first thing you need to do is install the Web3 library:

npm install web3

For the purpose of this tutorial, we are going to connect a MetaMask wallet to the website. To do that, here is the code to use:

if (window.ethereum) {
    const accounts = await window.ethereum.request({method: 'eth_requestAccounts'});

    const account = accounts[0]
    const web3 = new Web3(window.ethereum);
}

That code will open a MetaMask pop-up asking the user to accept the connection to his wallet.

If the user accepts, we store the connected account in a variable called account and we instantiate a Web3 object using window.ethereum (meaning the MetaMask wallet).

After that, we can run code when the selected wallet changes using this code:

web3.currentProvider.on('accountsChanged', (newSelectedAccount) => {
    // Do something here with newSelectedAccount
});

And that's it! 👏

Thanks for reading this article!