[SOLVED]Returning a result from a Smart Contract Function call with react

daiToken.methods.balanceOf(senderAddress).call(function(err, res) {
    if (err) {
        console.log("An error occured", err);
        return
    }
    console.log("The balance is: ",res);
})

Returns exactly what I want “res” and it is the correct value
However when I try

daiToken.methods.balanceOf(senderAddress).call(function(err, res) {
    if (err) {
        console.log("An error occured", err);
        return
    }
    return res;
})

It returns an error
I understand that the return type might be wrong, but how does console.log handle the datatype fine but if I try to cast to .toString() or BigInteger() both do not work. Neither does res.value or res.result

did you try res = await daiToken.methods.balanceOf(senderAddress).call()?

1 Like

Yes I have tried that, the thing is I want to return the result of the promise and display it to the screen via JSX like this {balance}

so something like this

res = await daiToken.methods.balanceOf(senderAddress).call()

in JSX

{res} or {res.result}

Or any variation

Now, the reason for the .call(function(err, res) is that when I console.log this “res” It displays the pure value “1” (the balance is 1) not an object/promise containing the 1, hence I thought that doing it this way was a better idea.

I am fully open to the idea that I am doing it all wrong or my approach is completely wrong. If that is the case then, just a brief link to a resource with a better approach would be appreciated

Try to use this logic:

const [daiBalance, setDaiBalance] = useState(0);

//function
daiToken.methods.balanceOf(senderAddress).call()
.then((balance) => setDaiBalance(balance))
.catch((err) => console.log("An error occured", err));

//component
<h2>{daiBalance}</h2>
1 Like

Worked. Bit of a moon landing moment really, I’ve been trying to get this to work for about 3 days. Just need the transfer function working then, we are ready for alpha. Thank you so much! Haha, bit ugly, but here is is a victory screenshot.

2 Likes

Nicee, great job :star_struck:

Happy BUIDLing :man_mechanic: