Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

274
Visualizações
web3js intercepting when metamask connects manually

Currently I have the following code to connect the metamask wallet in the browser (using reactjs and web3js):

function App() {
  const [contract, setContract] = useState();
    const [account, setAccount] = useState();
    const[web3Obj, setWeb3Obj]=useState();

  useEffect(()=>{

    async function load(){
        const web3 = new Web3(Web3.givenProvider || 'http://http://localhost:7545');
        setWeb3Obj(web3);
        const accounts = await web3.eth.requestAccounts();
        console.log(accounts[0] + " is the account");
        setAccount(accounts[0]);
       $.get( "getcontractaddress")
          .done(  function( data ) {


              const _contract = new web3.eth.Contract(abi, data);
              _contract.address = data;
              console.log(_contract.address + " is the contract");
              setContract(_contract);

          });



    }
     load();
  },[])

  return(
  
  );

}

I deleted the return(); part from the snippet because its irrelevant to the question.

Whenever I switch to a different account in metamask, the "account" object is not being updated. How can I intercept the event of metamask switching accounts to automatically reset the account object to the new account?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your component does not know when you switch accounts in Metamask. To detect account changes, Metamask provides the accountsChanged event.

ethereum.on('accountsChanged', handler: (accounts: Array<string>) => void);

You can add the event to your load function or make another useEffect. You can also remove the event when your component unmounts using ethereum.removeListener.

useEffect(() => {
    const { ethereum } = window;
    if (ethereum && ethereum.on) {
    
      const handleAccountsChanged = (accounts) => {
        console.log("accountsChanged", accounts);
        setAccount(accounts[0])
      };

      ethereum.on('connect', handleConnect);

      return () => {
        if (ethereum.removeListener) {
          ethereum.removeListener('accountsChanged', handleAccountsChanged);
        }
      };
    }
  }, []);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda