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 !");
}
};
I solved it by using the following code
declare global {
interface Window {
ethereum?: any;
web3?:any
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.