4

I am using React and trying to open Metamask wallet to sign and get the address of the user. However I tried this code and I've clicked the button to trigger it, but nothing happen.

This is my code with a component (a page) called Metamask

import React from "react";

export const Metamask = () => {
  const signMetamask = () => {
    if (window.ethereum) {
      window.ethereum.request({ method: "eth_requestAccounts" });
      console.log("MetaMask is installed!");
    }
  };

  return <button onClick={() => signMetamask()}>Open Metamask</button>;
};

If I click the button, I got the console.log result MetaMask is installed! but the metamask window is not opened.

Please help to make it work. Thank you

2 Answers 2

2
 async function requestAccount() {

    if(window.ethereum){
        try {
            const accounts = await window.ethereum.request({
                method: "eth_requestAccounts",
            });
            console.log(accounts)           
        } catch (error) {
            console.log(error)
        }
    }

}

Use async and await :) , dont forget * onClick={requestAccount) *

1

Looking at https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md#eth_requestaccounts calling eth_requestAccounts seems like an async operation. So following the example in the linked EIP you need to await the result. The result of this should be an array of addresses.

In any case if your MetaMask account was linked to your dapp (identified by the host) before, then it will not pop another popup.

1
  • 1
    Thanks for your reply Turns out I am already connected. So I need to disconnect first (user can only do it manually), then clicking the same button will open the metamask window to connect. Since I am already connected I can get the address by const ethacc = await window.ethereum.request({ method: "eth_accounts" }); console.log("etacc: ", ethacc); Another different thing that I just realized was Metamask Signature Request. This is the one that we use when logging in to Moralis. But it’s actually different purpose from connecting to metamask wallet. I might need it later too. Jan 1, 2022 at 13:37

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.