Hi, I am developing an NFT marketplace. I have a contract that has a function I can call to fetch the items that are on sale:
function fetchMarketItems() public view returns (MarketItem[] memory) {
uint itemCount = _itemIds.current();
uint unListedItemCount = _itemIds.current() - _itemsNotListed.current();
uint currentIndex = 0;
MarketItem[] memory items = new MarketItem[](unListedItemCount);
for (uint i = 0; i < itemCount; i++) {
if (idToMarketItem[i + 1].owner == address(this) && idToMarketItem[i + 1].status == ListingStatus.Active) {
uint currentId = i + 1;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
Also the contract has an event to be fired when a new item is listed like below:
event MarketItemCreated (
uint indexed itemId,
address indexed nftContract,
uint256 indexed tokenId,
address seller,
address owner,
uint256 price,
ListingStatus status
);
So I have two options to fetch the market data:
- Call the fetchMarketItems() function -> fetch the data -> parse/format the data and use on the frontend.
- Watch the smart contract event using Stream API -> Save to my Database when an event is fired -> Fetch the data from the database with appropriate filters-> Display on the frontend
My question is:
Considering I have implemented some other functions in the contract to fetch different types of items like onsale items, items with cancelled listing or sold, items of a specific seller etc.
- Which method would be better in terms of performance, reliability etc.
- Is it a good practice to fetch data from contracts?