1

Hello I'm very new to developing.

I'm testing communication with Metamask via React.js

I managed to succesfully listen to Network and Account changes, but when I try to detect if someone "connected" or "disconnected" from my App, I'm not able to receive the event.

Metamask API Documentation I'm using: https://docs.metamask.io/guide/ethereum-provider.html#connect

Working:

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

'

Not Working:

  • ethereum.on('connect', handler: (connectInfo: ConnectInfo) => void);
  • ethereum.on('disconnect', handler: (error: ProviderRpcError) => void);

the following Code is working flawless in my React.js app (using React.Component)

  async checkAccountChange() {
   const ethereum = window.ethereum
   if (ethereum) {
     // Listening to Event
     ethereum.on('accountsChanged', accounts => {
       console.log(accounts[0])
       this.setState({ account: accounts[0] })
  })
}

}

the following Code on the other hand is not giving me any console output

  async checkMetamaskHasConnected() {
    if (window.ethereum) {
      window.ethereum.on('connect', () => {
      console.log("Metamask connected")
      this.setState({ metamaskHasConnected: true })
  })
}

}

  async checkMetamaskHasDisconnected() {
    const ethereum = window.ethereum
      if (ethereum) {
      // Listening to Event
      ethereum.on('disconnect', () => {
        console.log("MetaMask discconnected")
        this.setState({ metamaskHasDisonnected: true })
  })
}

}

consider that I'm a very fresh beginner and just do learning by doing

1

If your requirement is:

detect if someone "connected" or "disconnected" from my App

the methods connect and disconnect you are trying might not help, as they are intended to know if your connection to the blockchain is available or not (for instance, when a user already connected tries to launch a transaction but the RPC connection is down).

Perhaps this post can help you. With the combination of getAccounts() and currentProvider you can deduce if a user is connected or not.

Otherwise, if this is only about knowing if a user is connected or not to your website, you may use WebSockets (depending on your architecture).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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