Attempting to execute a method from my smart contract on the ropsten test network has led me to an error within my getBalance() function:
Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'methods')
46 | async function getBalance() {
> 47 | const tempBal = await window.contract.methods.balanceOf(account.data).call()
| ^
48 | setBalance(tempBal)
49 | }
Establishing connection with my contract:
export default function ConnectContract() {
async function loadWeb3() {
if (window.ethereum) {
window.web3 = new Web3(window.ethereum)
window.ethereum.enable()
}
}
async function loadContract() {
const tempContract = await new window.web3.eth.Contract(ABI, ContractAddress)
return tempContract
}
async function load() {
await loadWeb3();
window.contract = await loadContract();
}
load();
}
The functions are currently being invoked as follows:
export default function Page() {
ConnectContract();
getBalance();
}
Previously, I successfully avoided the undefined error by using an onClick function within a button to trigger getBalance:
<div><button onClick={() => getBalance}>Get Balance</button></div>
It seems that the way I am calling them causes the getBalance function to be executed before the contract is connected to the website. Despite the current code working after a page refresh, I have yet to find a solution to ensure the contract is loaded so that the method is defined when getBalance is called.
I have attempted using onLoad and window.load() functions without success. I also tried calling my ConnectContract function in the _app.js file to load it upon website launch, but that did not yield successful results either.