Gelso77
Gelso77

Reputation: 1905

Solidity: return array in a public method

I am trying to create a public funcion that returns an array, this is the error

Return argument type mapping(uint256 => struct ItemList.Item storage ref) is not implicitly convertible to expected type (type of first return variable) uint256[] memory.

pragma solidity ^0.5.0;
contract ItemList {
    uint public itemCount = 0;
    mapping(uint256 => Item) public items;

    event ItemCreated (
        uint id,
        string proofdocument
    );

    struct Item {
        uint id;
        string proofdocument;
    }

    constructor() public {
    }

    function createItem(string memory _proofdocument) public {
        itemCount++;
        items[itemCount] = Item(itemCount, _proofdocument);
        emit ItemCreated(itemCount, _proofdocument);
    }

    function getItems() public pure returns(uint256[] memory ) {
        return items; <----------ERROR
    }
}

Thanks Andrea

Upvotes: 5

Views: 6820

Answers (1)

Yegor
Yegor

Reputation: 3950

You can get every item in the loop via web3.js library

const array = []
for (let i = 0; i < itemCount; itemCount += 1) {
    array.push(contract.getItem(i)) // where getItem do items[I] in solidity
}

Or you can use pragma experimental version:

pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;

contract ItemList {
    uint public itemCount = 0;

    struct Item {
        uint id;
        string proofdocument;
    }
    Item[] items;

    constructor() public {}

    function createItem(string memory _proofdocument) public {
        itemCount++;
        items.push(Item(itemCount, _proofdocument));
    }

    function getItems() external view returns(Item[] memory) {
        return items;
    }
}

Upvotes: 3

Related Questions