0

I have been trying to create a Web3 dApp using React.js. My first step was to connect the browser to a MetaMask wallet. So I first started by initializing a useState array variable named "wallets":

const [wallets, setWallets] = useState([])

After that, I made an async function, where if a button is clicked, this function will be ran:

async function connectWallets() {
    if (window.ethereum){
        const accounts = await window.ethereum.request({
            method:"eth_requestAccounts"
        });
        console.log("accounts", accounts)
        setWallets(accounts);
    }else{
        window.alert('Please consider installing Metamask')
    }

    console.log("wallets", wallets[0])

My problem is that when this function runs, the "accounts" variable contains the MetaMask wallet address, but when doing "setWallets(accounts)", the wallets variable is still undefined. What would be my error here?

Here is the console: enter image description here

1

1 Answer 1

1

This is happening due to a refresh of the website when click on connect wallet button, it pops up the metamask, there it will print the console log which you have written inside the function but when our wallet connects to the metamask then the page refresh and it resets the state.

So to overcome this issue, there are multiple ways to handle it or to preserve the state.

I have used useEffect which runs functions on every refresh, where it will check whether the user has metamask installed and is the user's wallet is connected to the metamask. useEffect will run on every refresh, so even if the page refreshes, we will run 1 more function to check whether our wallet is connected or not and accordingly we will get the correct status or updated states of wallet. Please refer below code

 const [currentAccount, setCurrentAccounts] = useState("");
 const [wallets, setWallets] = useState([]); //for you


  //Connect to wallet
  const connectWallet = async () => {
    try {
      const accounts = await ethereum?.request({
        method: "eth_requestAccounts",
      });
    
      setCurrentAccounts(accounts[0]);
      setWallets(accounts) //for you

      window.location.reload(); // i am forcing window to be refresh so that i can run the useEffect to run all my functions which are need to be run after connecting to wallet.
    } catch (error) {
      if (error.code === 4001) {
        console.log("User rejected the request");
      }
      throw new Error("No Ethereum object.");
    }
  };

  useEffect(() => {
    const checkIfWalletIsConnected = async () => {
      try {
        const accounts = await ethereum.request({ method: "eth_accounts" })

        if (accounts.length) {
          setCurrentAccounts(accounts[0]);
          setWallets(accounts) // for you
        } else {
          console.log("No Account Found");
        }
      } catch (error) {
        console.log("No Ethereum Found");
      }
    };

    const checkIfMetamaskInsalled = () => {
      if (!ethereum) {
        return setMetamaskInstalled(false);
      } else {
        return setMetamaskInstalled(true);
      }
    };

    checkIfMetamaskInsalled();
    checkIfWalletIsConnected();
  }, []);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.