Detecting Metamask account or network change in Javascript using Web3 1.0.0

A common issue in developing dApps is detecting which account within Metamask a user plans on using. At the time of this writing, even Metamask suggests you poll every 100 milliseconds. (Eww)

//Not a fun pattern to have to use
var account = web3.eth.accounts[0];
var accountInterval = setInterval(function() {
if (web3.eth.accounts[0] !== account) {
account = web3.eth.accounts[0];
}, 100);

Instead, the publicConfigStore exposed by the Metamask provider in web3 1.0.0 emits the “update” event. Hooking up to it as as simple as:

web3.currentProvider.publicConfigStore.on('update', callback);

Your callback will be called with an object containing the keys: {selectedAddress, networkVersion}. You can use this to easily listen for address or network changes and update your UI accordingly.

One caveat here is that the publicConfigStore is an unstable feature at the time of this writing due to the above linked README on Github suggesting the polling method. Just like everything else in crypto now, use at your own discretion!

Dream with me: