1

When I run my solidity function, it's supposed to return a string - but it returns [object Object] I'm calling the function in my frontend and logging the result of the function call.

Here is my solidity function call

function getResult() returns(string) {
  return result;
}

This is what I have on the frontend

async getResult() {
  let contractInstance = await MyContract.at(this.state.contractAddress)
  let result = await contractInstance.getResult()
  console.log(`This is the result ${result}`);
}
1
  • 1
    Why don't you print JSON.stringify(result, null, 4) and find out exactly what is "inside" that object? Commented Jul 23, 2018 at 6:14

4 Answers 4

2

This would do:

async getResult() {
  let contractInstance = await MyContract.at(this.state.contractAddress);
  let result = await contractInstance.getResult().call();
  console.log(`This is the result ${result}`);
}

Functions that do not require a transaction to be sent can be called directly.

0

Javascript returns [object Object] when you log out variables that are objects in templates or string concatenations. If you console.log('This is the result ', result); it will return the object itself, which will contain the string you are looking for.

The object will probably look like

{
    0: 'result'
}
5
  • So I need to do result[0] ? Commented Feb 28, 2018 at 21:46
  • Did you try logging out the result and checking? I think that result[0] will work, but I can't be sure off the top of my head.
    – wtk219
    Commented Mar 1, 2018 at 0:53
  • Yeah, I tried it and it returned undefined Commented Mar 1, 2018 at 1:32
  • Sorry to ask so many clarifying questions, you're saying that result returned undefined, or result[0] returned undefined?
    – wtk219
    Commented Mar 1, 2018 at 14:42
  • result returns undefined and result[0] throws an error because you can't have an index of 0 for undefined Commented Mar 1, 2018 at 21:25
0

I had the same issue, the problem is this line here:

let result = await contractInstance.getResult()

should be

let result = await contractInstance.getResult().call()

if you want to have a look at the json you can use inspect

import {inspect} from 'util'
console.log(inspect(result))
0

I have worked with web3JS (NodeJS). you can use this:

const Web3 = require("web3")
const web3 = new Web3("https://rpc-provider.....")

var MyContract = new web3.eth.Contract(abi, address);
MyContract.methods.getResult().call()
.then(console.log);

it will definitly console.log the string you want.

make sure you passed RPC-Provider, ABI & Contract Address.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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