Ali Raza
Ali Raza

Reputation: 113

Web3 metamask connection Cannot read properties of undefined (reading 'ethereum')

I have a react application in which I am trying to connect to metamask extension via web3. In my thunk.ts, I am calling the required functions but I am getting a type error that I cannot read the properties of undefined(reading 'ethereum'). Here is the code that I am using

if (window.ethereum) {//the error line
      window.web3 = new Web3(window.ethereum);

    try {
      await window.ethereum.enable();

      updateAddress(dispatch);
    } catch (err) {
      alert("Something went wrong.");
    }
  } else if (window.web3) {
    window.web3 = new Web3(window.web3.currentProvider);
    updateAddress(dispatch);
  } else {
    alert("You have to install MetaMask !");
  }
};

Here is the error screenshot

Here is the error screenshot

Upvotes: -1

Views: 3062

Answers (1)

Ali Raza
Ali Raza

Reputation: 113

I solved it by using the following code

declare global {
  interface Window {
    ethereum?: any;
    web3?:any
  }
}

Upvotes: 0

Related Questions