[Ethereum] the correct way to access public variable from contract in Truffle: then or standard callback

truffleweb3js

There are some similar posts to this but none seem to be able to solve my problem.

I have a contract deployed with Truffle running with testrpc.

I want to access the value of a public uint variable named gameStatus defined in the deployed contract game variable as such:

uint public gameStatus = 23;

I have found two ways to do this:

game.gameStatus(function(err, res){
    document.getElementById('amt').innerText = res;
});

And using the then operator from Promises.

game.gameStatus().then(function(result){
    document.getElementById('tableamt').innerText = result;
});

The first method never affects the value of 'tableamt' in the HTML. And the second method always yields a value of '0' in the HTML.

The contract in both cases deploys without errors and web3 does not complain.

Any help is much appreciated.

Thanks!

Best Answer

To get public variable value you need to use call. It is evaluated directly on local node without sending transaction to the blockchain. See also this great answer.

So, you need to call it that way:

game.gameStatus.call(function(err, res){
    document.getElementById('amt').innerText = res;
});
Related Topic