2

I have the following array in my smart contract:

string[] public saved_texts;

function getSavedTextsCount() public constant returns(uint) {
    return saved_texts.length;
}

I created getSavedTextsCount to basically get the length of my array.

My web3 function looks like the following:

  basicInfoUpdate: function () {
    TextContract.deployed().then(function (instance) {
      let element = ''
      for (let index = 0; index < instance.getSavedTextsCount; index++) {
        element += instance.saved_texts.call(index)
        element += '</br>'
      }

      document.getElementById('transactions').innerHTML = element
    })
  },

However, I do not get any result back. Any suggestions what I am doing wrong?

I appreciate your replies!

0

You are using the instance.getSavedTextsCount call in the wrong way

instance.getSavedTextsCount is an asynchronous method so you need to wait until it responds with a value.

the correct way to implement your idea will be :

var text_count;
instance.getSavedTextsCount.call().then(
   data => {
    text_count = data[0].c;
    var element ;
    for (let index = 0; index < text_count; index++) {
         instance.saved_texts.call(index).then(
            elemdata => {
              element += elemdata[0]
              element += '</br>'
            }
         )
        document.getElementById('transactions').innerHTML = element
      }


})

NOTE : please verify that data[0].c is existing, because usually that is what you get hen you call return uint from solidity using web3 call.

NOTE : is is better to use instance.getSavedTextsCount.call() than instance.getSavedTextsCount() when you are not adding data to storage, it uses less or no gas than the direct call, which should be reserved to methods that change storage.

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.