2

I'm trying to call different functions of a contract with a single function that has the function name passed to it as an argument.

var Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io'));
var myContract = new web3.eth.Contract(JSON.parse(data.abi), data.address);

var method = data.method // 'getWord'
myContract.methods.getWord().call().then(function(value) {
        console.log(value)
    }, function(error) {
        console.log(error)
    });

Above I have created a variable called method and its value has been set to getWord on the line below I am calling getWord()

What I'm trying to do is call whatever function is named in data.method like this...

    myContract.methods.[data.method].call().then(function(value) {
        console.log(value)
    }, function(error) {
        console.log(error)
    });

but of course it breaks and id prefer to not use eval() like this

    var myContract = new web3.eth.Contract(JSON.parse(data.abi), data.address);
    eval('myContract.methods.'+data.method+'().call()')  
    .then(function(value) {
        console.log(value)
    }, function(error) {
        console.log(error)
    });

Is there another way?

1

It should just be:

myContract.methods[data.method]().call()

(You had an extra dot in there.)

  • I tried without the dot and got TypeError: myContract.methods[data.method].call(...).then is not a function – Bill Oct 23 '17 at 5:22
  • Sorry, see my edit. I forgot to actually call the function. :-) – smarx Oct 23 '17 at 16:08

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.