1

My contract stores data in a mapping like the following:

mapping(address => uint256) public data_stores;

How can I view the data on a front end with web3js?

I have managed to view a uint256 like the below example.

uint256 public tester

the javascript

myContract.tester.call(function(err,res)
{
  console.log(res)
});

If I try the above for the mapping I get an error stating I have an invalid number of arguments for the solidity function. (I am assuming this is because I did not pass in an address for the mapping).

2

The mapping is public which means it gets a "free" getter that relieves the contract developer of the burden of writing it out. If it was written out (and we ignore the name conflict), it would look like this:

function data_stores(address index) public view returns(uint) {
  return data_stores[index];
}

As @Soham says, pass the address in so it knows which of the mapped uint values to return.

Borrowed from Soham (looks right to me ;-)

myContract.data_stores.call(address,function(err,res) {
  console.log(res)
});

Hope it helps.

0

You shall pass address to mapping data_stores to retrieve uint256 element stored in a mapping.

It is like a key value pair and you shall pass a key to get a value.

myContract.data_stores.call(address,function(err,res) { console.log(res) });

0

The public variables can be accessed as follows:-

 myContract.tester.call()
    .(then(function(tester) {
          console.log("Tester", tester);
 })
 .catch(function(err) {
          console.error("problem getting tester", err);
 });

In the case of mapping you have to create a get function in your contract and then call that function from your js

function getValueAtMapping(address userAddress)  public  constant  returns(uint value) {
      return data_stores[userAddress];
}

Then call the above function in your js by passing the address similar to above.

   myContract.getValueAtMapping.call(userAddress)
    .(then(function(tester) {
          console.log("Tester", tester);
 })
 .catch(function(err) {
          console.error("problem getting tester", err);
 });

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.