0

I have created a struct patient as follows, and a mapping of uint->patient.

struct patient {
    uint pId;
    string name;
    string phone;
    address payable owner;
    uint numRecords;
    uint[] cost;
    address[] uploader;
    string[] procedure;
    uint[] hospId;
    string[] doctorName;
    bool[] treated;
    string[] image;

}


mapping(uint => patient) public patients;

I am have created functions to insert data into the mapping. However, when i try to read the data in reactjs using web3,

//REACTJS     
for (var i = 1; i <= patientCount; i++) {                                                 
            const patient = await container.methods.patients(i).call()
    }

the patient variable only contains the non array parts of the struct. i.e, only pId, name, phone, owner and numRecords is returned.

The value returned is

 {0: BigNumber, 1: "Name", 2: "1234567890", 3: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06", 4: BigNumber, pId: BigNumber, name: "Name", phone: "1234567890", owner: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06", numRecords: BigNumber}
0: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
1: "NAme"
2: "1234567890"
3: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06"
4: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
name: "Name"
numRecords: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
owner: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06"
pId: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
phone: "1234567890"
__proto__: Object

1 Answer 1

1

In order to return the whole struct you need to use the ABIEncoderV2 and define your own getter function

pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;

contract Foo {

  function getPatient(uint id) public view returns (patient memory) {
    return patients[id];
  }
}

2
  • Exactly what i was looking for, Thank you. Out of curiosity, is there any way to do this in a single funciton without using experimental features? Without using seperate funcitons for each parameter atleast.. Jun 3, 2020 at 11:29
  • @FarhadBharucha With current solc 0.6 you have to use experimental pragma and a separate function, perhaps in a future version they will make it the default choice but it is not possible yet.
    – Ismael
    Jun 3, 2020 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.