Solidity – How to Call Array Variable in Web Application

blockchainethereum-wallet-dappethereumjssolidityweb3js

I have declared one array inside solidity contract like "uint256[] public machineList; " and initialize the values of that array inside the constructor.

But when I call that array inside js usgin web3 mentioned as below :

AssetContract.deployed().then(function(contractInstance) {

    let getMachineList = contractInstance.machineList;
    alert(getMachineList);
});

It is returning below output in getMachineList variable:

    function () {
  var instance = this
  var args = Array.prototype.slice.call(arguments)
  var tx_params = {}
  var last_arg = args[args.length - 1]
  if (Utils.is_object(last_arg) && !Utils.is_big_number(last_arg)) {
    tx_params = args.pop()
  }
  tx_params = Utils.merge(C.class_defaults, tx_params)
  return C.detectNetwork().then(function () {
    return new Promise(function (accept, reject) {
      var callback = function (error, result) {
        if (error != null) {
          reject(error)
        } else {
          accept(result)
        }
      }
      args.push(tx_params, callback)
      fn.apply(instance.contract, args)
    })
  })
}

this type of data I am getting in alert(contractInstance.machineList);

So, how can we get array values in side JS without making explicit getter function inside solidity rather to call in built in getter function which is provided by solidity for state variable ?

Best Answer

You can get dynamic array like this : uint256[] public machineList by creating a contract getter function.

function getMachineList () external returns (uint256[]){
return machineList
}

note the external modifier i added, in this kind of functions where you are returning a dynamically sized array the external modifier is mandatory. it also makes the function only callable from the exterior of the contract which is exactly what we want here.

An other thing is that you are using truffle to call contract functions. When using truffle you need to call a promise (or a callback) after the name of the function :

AssetContract.deployed().then(function (contractInstance) {

  contractInstance.getMachineList.
  call(**arguments if any**,{ from:**address**, gas: 300000 }).then(
    data => {
      var MachineList = data;
      alert(MachineList);
    }
  )

})

Note: whenu sing truffle you add the .call() if you are just calling functions that read and return variables as if it will not alter state variables (change/add existing/new value).

Related Topic