Prerequisite: A beginner-level understanding of Ethereum and web3.js.
User experience is one of the biggest roadblocks to onboarding users onto your decentralised application (DApp). Modern web browsers don’t support web3 by default, so most users have to interact with DApps via the Metamask browser extension.
Metamask allows users to alter the network and change their active wallet address from the extension.
Figure 1
Unfortunately, DApps won’t know when the user changes an account without specifically checking for it. This means that if a user changes accounts whilst using your DApp, they will be presented with out-of-date information relating to the previous account. This is like logging into your Facebook account and seeing the previous user’s dashboard. It is obviously unacceptable.
Fortunately, Metamask now allows you to listen for when a user changes their account in real-time with a simple piece of code.
Detecting Account Change
Let’s assume that you have a function called getAccount() that connects to Ethereum and loads the active account being used. This occurs whenever the DApp is loaded.
Metamask fires an accountsChanged event upon account selection changing, which we can listen for. Figure 2 shows what the code for this looks like:
async function getAccount() {
const accounts = await ethereum.enable();
const account = accounts[0];
// do something with new account here
}
ethereum.on('accountsChanged', function (accounts) {
getAccount();
})
Figure 2
Using this event listener enables your DApp to get the latest wallet data in real-time, making your user experience slick and up to date. Figure 3 shows a DApp that retrieves the active wallet address and displays it in a button when the accountsChanged event is fired.
Figure 3: Click image to activate gif
For more information on this feature, see Metamask’s documentation.
Learn More
If you’re interested in Blockchain Development, I write tutorials, walkthroughs, hints, and tips on how to get started and build a portfolio. Check out this evolving list of Blockchain Development Resources.
If you enjoyed this post and want to learn more about Blockchain Development or the Blockchain Space in general, I highly recommend signing up to the Blockgeeks platform. They have courses on a wide range of topics in the industry, from Coding to Marketing to Trading. It has proven to be an invaluable tool for my development in the Blockchain space.