0

I have a smart contract that contains posts. Let's say that it's a twitter-like dapp.

Contract Blog {
    struct Post {
        string content;
        bool isDeleted;
    }
    mapping (uint256 => Post) private posts;
    uint256 postCounter = 0;
}

In this contract, I have a get method that returns post if post is not deleted.

function get(uint256 index) public view returns (string memory) {
    Post memory post = posts[index];
    required(post.isDeleted == false, "This post is deleted.")
    return post.text
}

In this case, when I need to loop over Tweets I'm something like this on the frontend.

Get num of posts from the contract = X
for (let i=0; i<=X; i++) {
   try {
       post = try to get post from contract.
   } except {
       if contract returns error suppress it
       continue
   }
}

Most of the time the frontend side is trying to consume the contract for non-existing posts. Is there any better approach to do this?

3
0

I have solved this by returning deleted posts with a flag.

function get(uint256 index) public view returns (bool, string memory) {
    Post memory post = posts[index];
    return (post.deleted, post.text)
}

Then after on frontend side I'm using that deleted flag to not to show.

Get num of posts from the contract = X
for (let i=0; i<=X; i++) {
    isDeleted, text = try to get post from contract.
    if (isDeleted) {
        continue (or show an empty post that describes that is deleted)
    } else {
        render post
    }
}

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.