0

This is to interact with my smart contract. My contract has a function like this e.g:

function getOfferById(uint256 _tokenId) public view returns (uint256) {
    require(_tokenId < MAX_B, "This tokenId does not exist");
    uint256 offer = bOffers[_tokenId];
    require(offer > 0, "There is no offer for this token");
    return offer;
}

Now what is to query this data on page load or whenever a new event comes and this data might have changed, I did it like this:

useEffect(() => {
    async function getOfferById() {
      if (myContracts) {
        const _getOfferById = myContracts.getOfferById;
        if (_getOfferById && id) {
          try {
            const _offer = await _getOfferById(id);
            setoffer(formatUnits(_offer, 'ether'));
          } catch (e) {
            setoffer(0);
          }
        }
      }
    }
    getOfferById();
  }, [myContracts, id, myEventOfferCreated, myEventOfferCanceled]);

But this way, I get a lot of console errors all the time from my metamask, because the require statement hits often.

What would be the best way to this?

1

I always prefer to prevent require statements in view methods, unless it's really necessary. Because sometimes, backends like Metamask, due to some limitation, don't include the revert reason strings in the error, which causes user interfaces to have a hard time figuring out the cause of the error.

I'd instead suggest you to change your method to:

function getOfferById(uint256 _tokenId) public view returns (
  uint256 offer, bool tokenExists) {
    offer = bOffers[_tokenId];
    tokenExists = _tokenId < MAX_B;
}

So if tokenExists is false, you can display that in UI. Also if offer === 0, then you can display in UI that there is no offer.

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.