I have made a simple contract function where a user can write a message and then submit it to the array in the contract Messages
:
string[] public Messages; function WriteMessage (string MessageInput) public { Messages.push(MessageInput); }
On the frontend, I want to print in order all of the messages contained in the array. With one message it is very simple, you just write the call via Web3.js like this:
Contract.WriteMessage(0, function(error, result) { if (!error) { $("#messagediv1").html("" + result); } else console.error(error); });
It's a bit confusing the syntax, but the 0
represents the first entry into the Messages
array. In the div with the ID messagediv1
, you will see the very first message printed. If you omit the entry number it will error. You cannot just download the whole array and then write something like this:
Contract.WriteMessage(function(error, result) { if (!error) { $("#messagediv1").html("" + result[0]); $("#messagediv2").html("" + result[1]); $("#messagediv3").html("" + result[2]); $("#messagediv4").html("" + result[3]); } else console.error(error); });
Is there a way to do a for loop on the this dynamic array until a result returns as invalid/null/0?
Note: Writing a getter function for the array does work, but you must transact each time to retrieve everything in the array.