Function to return the mapping of all people?

Building on top of the sample HelloWorld dapp we’ve built. . . what would be the best way to get a list of all People ? I wasn’t able to simply return a mapping.

Ultimately i’m building the front end and need the complete list of all people . . . Should this be handled more by the Javascript via a Web3 call ??

I think you could use web3 to query the mapping and through a for run it until it loads the whole list

2 Likes

Can someone help me out here? i think there’s something i don’t understand. I’m a newb.

mapping (address => Person) public people;

How can this be accessed from JS?

console.log(myContract);
console.log(myContract.methods.people(1));
console.log(myContract.methods.people(1).call);
console.log(myContract.methods.people(1)._method.outputs);

@bhaun
You can access a public mapping variable like a regular public variable with the exception that you need to provide the index value for the mapping.

After the contract address instance:

const contract = web3.eth.contract(abiArray).at(contract_address);

access these variable using the following web3 javascript code:

contract.people.call('address you want to pass in mapping', function(err, result){
     if(!err){
        console.log(result)
     }
 });

Hope this answers all the previous question as well.

Happy coding :+1:

@Taha Thanks… but, I’m not getting this to work for me.

Uncaught (in promise) TypeError: Cannot read property 'call' of undefined

@bhaun
Yes, this should be handled more by Javascript.
Because js helps us to keep most of the operations and validation on the browser side reducing the load on the server-side (EVM in our case).

@bhaun
I suggest sharing your code via Github, so I can reproduce the error and come back to you.

Thanks

Thanks @Taha I was not able to get that to work… turns out everything i tried to do was a can-of-worms. … not the Struct, nor Mapping, nor Array.

The solution I end up creating was calling the Web3.getPastEvents(); what a cool feature. I’m sure there are more sophisticated solution, but this is good for my newbie purposes.

myContract.getPastEvents('personCreated', { fromBlock: 0, toBlock: 'latest' }, function (error, event) {})
            .then(function (event) {
                let n = event.length;
                for(var i= 0; i<n; i++){
                 console.log(event[i].returnValues.name);
                }
            });
1 Like