I am using ReactJS+Metamask for the web UI development. Since Metamask doesn't support synchronous approaches, I need to use callback functions to get my public variables. I found that with in the callback function, both alert()
and console.log()
can represent the correct variable. However, I want to store the value in an variable and display it in a list. But it seems that I cannot return this value or assign it to an existing variable.
Here is the code where numIssuer
is a public variable in my contract. num
will represent as undefined if I use console.log(num)
after this:
var num = myContract.numIssuer(function(err,res){
num = res;
});
or
var num;
myContract.numIssuer(function(err,res){
console.log(res);
});
I am very new for front-end development. Is the problem with React or with web3?
Best Answer
You probably does not understant the asynchronous nature of your call. In the following example,
Line A
is executed afterLine B
. Thats why inLine B
you will seeundefined
:You need to put received value into the list inside callback, not after the call like this: