This is the function from my smart contract:
uint public numberOfFoods;
function returnNumberOfFoods() external view returns(uint){
return numberOfFoods;
}
I am trying to fetch numberOfFoods using web3. This is my JS code:
const Web3 = require('web3');
const FoodOrder = require('../../build/FoodOrder.json');
const foodItems = async ()=>{
const web3 = new Web3(window.ethereum);
const networkId = await web3.eth.net.getId();
const myContract = new web3.eth.Contract(
FoodOrder.abi,
FoodOrder.networks[networkId].address
);
const numberOfFoods = await myContract.methods.returnNumberOfFoods().call();
return numberOfFoods;
}
export default foodItems;
After receiving the promise, this is what I'm using to fetch the returned value:
import foodItems from "./helpers/number_of_food_items";
foodItems()
.then(data => {
console.log(data); //this always return 0
})
.catch(error => {
// Handle/report error
});
Note: There are other functions in my smart contracts that change the value of numberOfFoods. I've checked those functions and they're changing the value of numberOfFoods correctly as expected. It seems that the problem is with the particular returnNumberOfFoods() function or my JS driver code.