0

My smart contract function is :

function sNName(uint z)public view returns(string memory) {
    return abc[xyz[z].name];
}

Where abc represents a mapping (bytes32 => string)

In my .js file, I called the function like this:

for(x=0 ;x < t; x++)
{
  n = await marketplaceContract.methods.sNName(x).call().toString();
  this.setState(prevState => ({
    cart: [...prevState.cart, n]
  }));
}

When I try to output cart, I get :

[object Promise]

I expected a string cos I have used await. Is there any mistake in using it inside a loop?

Please help.

  • As far as I can tell you are calling .toString to the promise and after that awaiting it, which doesn't make sense. Try n = (await marketplaceContract.methods.sNName(x).call()).toString(); – Lauri Peltonen Jul 5 at 5:54
  • Thanks @LauriPeltonen. I get your point. But after doing that, there's no output. I mean now it's completely blank. – Shailesh Mishra Jul 5 at 7:04
  • But when I am storing in cart[] a fixed string, in place of n and then printing it, it's printing the fixed string. – Shailesh Mishra Jul 5 at 7:37
0

Change this:

n = await marketplaceContract.methods.sNName(x).call().toString()

To this:

n = (await marketplaceContract.methods.sNName(x).call()).toString()

BTW, I believe that n is a string already before you call toString().

If I'm right, then you can simply do:

n = await marketplaceContract.methods.sNName(x).call()

Your problem in general is that the toString() part takes precedence over the await part, so you are essentially trying to apply toString on a Promise object.

  • Thanks a lot for explaining the part about what my toString() is doing. I did as you told. In my front-end, nothing is showing up when I am returning in my render(). It's really curious. – Shailesh Mishra Jul 5 at 9:21
  • @ShaileshMishra: You're welcome. The question here is not about your front-end (and it would be missing a lot of context & details if it were). So I suggest that you post it as a separate question. – goodvibration Jul 5 at 9:24
  • Okay sure will do that – Shailesh Mishra Jul 5 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.