The accountChanged event isn’t working on ethers Providers #1560
Replies: 3 comments 4 replies
-
The You will need to use the For a list of events that ethers providers, see this link. Does that make sense? :) (moving to discussions) |
Beta Was this translation helpful? Give feedback.
-
Thanks a lot. This works. const setAccountListener = (provider) => {
provider.provider.on("accountsChanged", (accounts) => {
setAccount(accounts[0]);
});
}; |
Beta Was this translation helpful? Give feedback.
-
Without using ethers.js provider, you can monitoring account change event for browser wallet.// Check if MetaMask is available
if (typeof window.ethereum !== "undefined") {
// Listen to account change events
window.ethereum.on("accountsChanged", (accounts) => {
console.log("MetaMask account changed:", accounts[0]);
});
} else {
console.log("MetaMask not detected");
} Secondly, update ethers.js version and try following code.import { ethers } from 'ethers';
// Create an ethers provider using Metamask as the provider
const provider = new ethers.providers.Web3Provider(window.ethereum);
// Request permission to access accounts
window.ethereum.request({ method: 'eth_requestAccounts' })
.then((accounts) => {
// Listen for the 'accountsChanged' event
provider.on('accountsChanged', (newAccounts) => {
// Handle the account change event
console.log('Account changed:', newAccounts[0]);
});
})
.catch((error) => {
// Handle error if permission is denied
console.error('Permission denied:', error);
}); |
Beta Was this translation helpful? Give feedback.
-
In ethers version 5.1.4, a way of subscribing to Metamask (Web3Provider) events is broken:
The example:
Full working example:
Ways to reproduce:
Beta Was this translation helpful? Give feedback.
All reactions