Skip to content

Incorrect code in the connect function #9

@ShariqKhan2012

Description

@ShariqKhan2012

The connect function in the file index.js is a bit incorrect:

async function connect() {
  if (typeof window.ethereum !== "undefined") {
    try {
      await ethereum.request({ method: "eth_requestAccounts" })
    } catch (error) {
      console.log(error)
    }
    connectButton.innerHTML = "Connected"
    const accounts = await ethereum.request({ method: "eth_accounts" })
    console.log(accounts)
  } else {
    connectButton.innerHTML = "Please install MetaMask"
  }
}

The following lines should be inside the try block, before the catch block:

connectButton.innerHTML = "Connected"
const accounts = await ethereum.request({ method: "eth_accounts" })
console.log(accounts)

With the current code, if the user clicks the Cancel button (or closes the MetaMask popup) when MetaMask requests permission to connect, the button's label still changes to Connected, which is misleading.

If the above 3 lines are moved inside the try block, this problem will be fixed

async function connect() {
  if (typeof window.ethereum !== "undefined") {
    try {
      await ethereum.request({ method: "eth_requestAccounts" })
      connectButton.innerHTML = "Connected"
      const accounts = await ethereum.request({ method: "eth_accounts" })
      console.log(accounts)
    } catch (error) {
      console.log(error)
    }
  } else {
    connectButton.innerHTML = "Please install MetaMask"
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions