Solidity – How to Return an Array from a Smart Contract Function in Web3js and React

contract-invocationreactsolidityweb3js

Yo I'm pretty new to coding so bear with me. I'm using ReactJS with web3 to call functions from a smart contract but the function I'm trying to call returns an array and I can't figure out how to return the array using web3.

When I try to call the function it just returns:

Object { 0: "0x0000000000000000000000000000000000000000", 1: [], tokens: [] }
const ownedTokens = () => {
  blockchain.smartContract.methods
    .ownedTokens()
    .call().then((tokens) => {
      console.log(tokens)
    });
};

This is the solidity function I'm trying to call


function ownedTokens() public view returns(address, uint256[] memory tokens){
  return(msg.sender, addressesVault[msg.sender].ownedTokens);
}

and the struct it's taking from

struct addresses{
        uint256[] ownedTokens;
    }

    mapping(address => addresses) addressesVault;

Best Answer

The reason is because msg.sender is set to 0x0000000000000000000000000000000000000000 when you use the call method. So you should set from value when calling the call method to set msg.sender like this:

    const ownedTokens = () => {
  blockchain.smartContract.methods
    .ownedTokens()
    .call({from: '0x1a7d5bF03d2a72494B9487fF0E0B9491c13965B4'}, function(error, tokens){
        console.log(tokens); 
   });;
};

In place of 0x1a7d5bF03d2a72494B9487fF0E0B9491c13965B4 set the address you want the msg.sender to be.

Ref