0

I want to return an array of structs because i want to output all my data.

//SPDX-License-Identifier:MIT
pragma solidity ^0.8.0;

contract MyContract
{
    mapping(uint256 => People) dataList;
    uint256[] countArr;
    struct People{
        string name;
        uint256 favNum;
    }

In this function, i set the data of my struct object and then include it in my mapping.

    function setPerson(string memory _name,uint256 _id, uint256 _favNum) public {
        dataList[_id]= People(_name,_favNum);
        countArr.push(_id);
    }

This function here gets me the data of my specified struct object.

    function getPerson(uint _id) public view returns(string memory,uint256){
        return (dataList[_id].name, dataList[_id].favNum);
    }

Now here is the function i think that is causing me trouble because in this function i want to return not the data of a single People object but all of my data and whenever i run this function on my REMIX IDE console it shows me the error: call to MyContract.getAllData errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance.

    function getAllData()public view returns(People[] memory){
        uint256 count = countArr.length;
        uint256 i = 0;
        People[] memory outputL= new People[](count);
        while(count >= 0){
            (string memory nam,uint256 num) = getPerson(count-1);
            People memory temp = People(nam,num);
            outputL[i]=temp;
            count--;
            i++;
        }
        return outputL;
    }                
}

Can anyone help and explain what is wrong and how can i get it running?

  • please refer this question [here](https://stackoverflow.com/questions/72943448/how-to-return-an-array-of-structs-from-solidity/72947216#72947216) – Naren Murali Jul 14 '22 at 16:15

1 Answers1

0

This version of the getAllData function works as you expect:

    function getAllData() public view returns (People[] memory) {
        uint256 count = countArr.length;
        People[] memory outputL = new People[](count);

        while(count > 0) {
            count--;
            (string memory nam, uint256 num) = getPerson(countArr[count]);
            People memory temp = People(nam, num);
            outputL[count] = temp;
        }

        return outputL;
    } 

Feel free to ask if you have any questions about the changes.

Igor Senych
  • 56
  • 1
  • 3