I am trying to develop a new Dapp. I have written the smart contracts and they are working well. I now need to use web3 to interact with the smart contracts, for now using ropsten or rinkeby.
I get the error "Uncaught TypeError: myCollection.methods.getNumberObjects.call(…) is not a function"
Here is the relevant code:
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
<script language="javascript" type="text/javascript" src="collection_abi.js"></script>
window.addEventListener('load', function() {
window.ethereum.enable();
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// Use MetaMask's provider
web3js = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers - Ropesten
web3js = new Web3.providers.HttpProvider("http://localhost:3000");
}
web3js.eth.defaultAccount = web3js.eth.accounts[0];
// Now start app:
startApp()
})
…
function startApp() {
collectionAddress = '0xaff...'
myCollection = new web3js.eth.Contract(collectionABI, collectionAddress);
updateCollection();
}
Here is what I loaded on my windows pc:
- yarn lite-server
- yarn node
- yarn node-gyp
- yarn web3
- yarn web3-eth
Here is package.json:
{
"name": "Test",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "lite-server",
"test": "echo "Error: no test specified" && exit 1"
},
"repository": "https://github.com/prutovitz/Test.git",
"author": "Philip Rutovitz [email protected]",
"license": "MIT",
"dependencies": {
"lite-server": "^2.6.1",
"node": "^16.10.0",
"node-gyp": "^8.2.0",
"web3": "^1.6.0",
"web3-eth": "^1.6.0"
}
}
Where I get the actual error is:
// Update Collection data
function updateCollection() {
myCollection.getNumberObjects (function(errGNO, resGNO) {
getNumberObjects is defined as:
function getNumberObjects() public view returns(uint) {
return objects.length;
} // function getNumberObjects()
It seems like web3 is not connecting properly although I do not get an error.
Can anyone help me?
Thanks!
Best Answer
As far as I can see, I don' see anywhere in your code the syntax where you're actually calling the method. You have the instance of the contract which is
myCollection
but you're not calling the function properly. instead of this:you can try this:
let collection = myCollection.methods.getNumberObjects().call()
Maybe look into class components and functional components for react.js.I think it's a better approach than what you have now. Here's a link to make an idea: https://www.pluralsight.com/guides/manipulating-arrays-and-objects-in-state-with-react