useState not updating my variable and other solutions aren’t working either


This Content is from Stack Overflow. Question asked by asusrid

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) {
}, [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) {

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", []);
      return provider;
    } catch (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!!!!


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?