0

I tried to read a list of posts using the code below

struct posts {

  bytes32 postTag;
  string post;
  address[] acceptedBy;
  uint8[] voteCount;

}

mapping(address => posts) totaluserPosts;

I tried to read all the posts in different ways but couldn't find a way to do.

Is it possible to read all the posts through one request?

  • Are you trying to return an array of the struct posts? – vhie Oct 30 '18 at 1:42
0

The short answer is you have to create a function because the "free" getter you receive via the public mapping doesn't do this.

A better answer is to reconsider the need for the bulk data dump. I will usually suffice if you emit events each time something is inserted into this structure and that means software clients should already be informed about this information. Ergo, why ask for it again given that doing so is gas-intensive and not especially fast. A more complete description of this thinking: https://blog.b9lab.com/the-joy-of-minimalism-in-smart-contract-design-2303010c8b09

Suggestion. Naming conventions:

struct PostStruct {

  bytes32 postTag;
  string post;
  address[] acceptedBy;
  uint8[] voteCount;

}

mapping(address => posts) postStructs;

Custom function examples:

function getPostAddressCount(address post, uint row) public returns(uint count) {
  return postStructs[post].address.length;
}

function getPostAcceptedBy(address post) public returns(address[] acceptedBy) {
  return postStructs[post].acceptedBy;
}

Since the cost of the above function increases with scale to the point of being unworkable, it is a good idea to include a fixed-cost alternative:

function getPostAcceptedByByRow(address post, uint row) public returns(address acceptedBy) {
  return postStructs[post].acceptedBy[row];
}

Hope it helps.

| improve this answer | |
  • can you explain what you meant by mapping (address => posts) postStructs? @Rob Hitchens B9lab – Girish Oct 30 '18 at 2:38
  • Corrected it for consistent renaming. – Rob Hitchens Oct 30 '18 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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