Hardik Mehta
Hardik Mehta

Reputation: 111

Cannot Read Property Error(Can't call Function getNum)

The Contract is given above the html file code. It's basically getting and setting numbers. I have used promises in my code. Is that the problem? The ABI is correct as well as the Contract Address. I have used web3.currentProvider because i am using metamask. I am a beginner in blockchain.

pragma solidity ^0.5.0;

contract sample {

    uint number;
    constructor () public {
        number = 5;
    }
    function getNum () public view returns (uint) {
        return number;
    }

    function setNum (uint n) public {
        number = n;
    }
}

At console, Error:

Uncaught TypeError: Cannot read property 'getNum' of undefined
at index.html:51

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test for Web3</title>
    <!--<script src="https://cdn.jsdelivr.net/npm/[email protected]/src/index.min.js"></script>-->
</head>
<body>
    <script>
        var web3;
        web3 = new Web3(web3.currentProvider);
        var contract = web3.eth.contract(
            [
    {
        "constant": false,
        "inputs": [
            {
                "name": "n",
                "type": "uint256"
            }
        ],
        "name": "setNum",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "constructor"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "getNum",
        "outputs": [
            {
                "name": "",
                "type": "uint256"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    }
],"0x0c094f6ffbf8dbfde107e819e5060c509eab8951");
    contract.methods.getNum().call().then(function(result){
        console.log("Number: " + JSON.stringify(result));
    });
    </script>
</body>
</html>

Upvotes: 1

Views: 144

Answers (1)

olegabr
olegabr

Reputation: 535

Looks like you are using 1.X web3.js version. Use var contract = new web3.eth.Contract in this case. See https://web3js.readthedocs.io/en/v1.2.0/web3-eth-contract.html for more info:

new web3.eth.Contract(jsonInterface[, address][, options])

Upvotes: 1

Related Questions