Detecting Metamask Account Changes and Lockouts with React
As a React developer, you probably know how important it is to keep track of changes to user accounts and wallet balances. In this article, we will explore how to detect when a user’s MetaMask account has been changed or locked.
Problem: window.ethereum.on('accountsChanged', function (accounts) { ... });
is not working
Your approach. using the “accountsChanged” event is a good start, but there are a few additional steps you need to take to achieve what you are looking for. Here is an updated example to help you:
import React from 'react';
function MetamaskDetector() {
const const = useMetaMaskAccounts();
useEffect(() => {
async return () => {
const const = await getAccountList();
// Update the "accounts" state with the current list of MetaMask accounts
setAccounts(accounts);
// Check for changes in the account list and update the display accordingly
checkChangesInAccounts(accounts);
};
}, []);
asynchronous function getAccountList() {
// Implement a function to retrieve a list of current accounts from MetaMask
// For demonstration purposes, let's assume this function returns an array of accounts
const const = ['account1', 'account2', 'account3'];
returned accounts;
}
asynchronous function checkForChangesInAccounts(accounts) {
const newAccounts = [];
const oldAccounts = [...accounts];
accounts.forEach((newAccount, index) => {
if (oldaccounts[index] !== newaccount) {
console.log(Account ${newAccount} changed or blocked!
);
// You can also update the display to indicate this change
// for example, show a red fill effect on the old account
alert(Account ${newAccount} has been changed or blocked. Please check the status of your wallet.
);
}
}
useMetaMaskAccounts();
return (
{accounts.map((account) => (
{account}))}
{checkForChangesInAccounts(accounts)}
);
}
What’s changed?
Important notes:
Following this updated example, you should now be able to detect when your users’ MetaMask accounts have changed or been locked. Don’t forget to replace the hard-coded array of “account1”, “account2”, and “account3” in the “getAccountList” function with a reliable method to retrieve the current list of accounts from MetaMask.