[Ethereum] Metamask API: can’t detect events “connect” and “disconnect” in React.js

eventsmetamaskreact

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

Best Answer

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).