I know there are plenty of answers related to this topic but I've tried all of them, using useEffect, and it still doesn't work. What I'm trying to do is to update a variable called currentAccount when the app loads and then each time the account changes (this is an app using Metamask).
So when the website loads:
useEffect(() => {
if (!walletConnected) {
[...]
onPageLoad();
}
}, [walletConnected,currentAccount]);
Then, as can be seen, I connect to the connect, select the role of the user logged and there is a listener Metamask provides that listens to an event called 'accountschanged' and when that event is triggered, changes the currentAccount state and again check the role of the new account.
const onPageLoad = async () => {
await connectWallet();
await getUserRole();
window.ethereum.on('accountsChanged', function (accounts) {
setCurrentAccount(accounts[0]);
getUserRole();
})
};
The connectWallet is the one responsible for the first time to update the currentAccount from the default value '' to the current account. The problem is that it doesn't update the value...
const connectWallet = async () => {
// we need to gain access to the provider/signer from Metamask
try {
const provider = await getProviderOrSigner();
let accounts = await provider.send("eth_requestAccounts", []);
setCurrentAccount(accounts[0]);
setWalletConnected(true);
return provider;
} catch (error) {
console.log(error);
}
};
What am I doing bad?? Any idea? I can share with you more code if needed. I know it's a long question but I wanted to give as many details as needed.
Thanks a looott!!!!