Search code examples
reactjssolidityweb3js

Unable to call function from smart contract using web3.js


I am trying to call a function from my smart contract using web3 and react. Here is my code.

app.js
    const project=new web3.eth.Contract(Mycontractabi.abi,networkData.address);
    const retailer=await project.getretailer.call();
    console.log(retailer);

contract:
    address public  retailer
    function getretailer() public view returns (address)
    {
        return retailer;
    }

Kindly point out what is wrong as I am not able to get retailer address as desired by the code


Solution

  • I found that to access a variable from a smart contract using web3.js there is simple method:

    contract.methods.variable_name.call().call();
    

    So in my case, the modified code will be :

    const project=new web3.eth.Contract(Mycontractabi.abi,networkData.address);     
    const retailer=await project.methods.retailer.call().call();
    

    There is no need to call any function just to access a single variable. We can access any variable directly by using above method.