NFT Collection Explorer on NEAR.Social

Joshua OwenJoshua Owen
Mar 17, 2023|4 min read

Once upon a time, in the digital realm of NEAR.Social, there was a desire to create a magnificent and open sourced NFT collection explorer that would fetch and visualize data using the powerful Indexer API. In this enchanting tale, we'll accompany you on a journey through the creation of a user-friendly interface that allows users to enter a specific collection slug, discover the collection's captivating details, and marvel at a gallery of NFTs, sorted by listing price and status.

A Journey Through the Magical Realm of NFT Collection Exploration with NEAR.Social and the Indexer API

The Beginning: Preparing for the Adventure

To embark on this magical quest, you'll need:

  • A basic understanding of JavaScript and React's mystical powers
  • A basic understanding of the unique restrictions of the NEAR.Social development environment

🔗 See full source code here

Step One: Conjure the Application State

First, like a skilled sorcerer, you must conjure the application state with the following properties:


initState({
  inputCollectionSlug: "asac.near",
  collectionSlug: "asac.near",
  collectionData: {},
  nftData: [],
});

Step Two: Unleash the Fetch Data Function

Imagine yourself as an alchemist, preparing to unleash the formidable fetchData function, a spell capable of retrieving NFT collection data from the mystical Indexer API. Like a conjurer summoning spirits, this enchanting incantation sends a POST request to the API endpoint with the required headers and a GraphQL query.

First, you must clear the canvas by updating the nftData state to an empty array, ensuring you start fresh:


State.update({ nftData: [] });

As you chant the spell, you send the POST request to the API endpoint, imbuing it with the required headers—such as the cryptic API key and content type—unraveling the secrets of the Indexer API:

let response = fetch("<https://byz-multi-chain-01.hasura.app/v1/graphql>", {
  method: "POST",
  headers: {
    "x-api-key": "ChRbeKE.c94220449dbb45973a67a614b1f590be",
    "Content-Type": "application/json",
    "Hasura-Client-Name": "near-social",
  },

In the heart of the request, you weave a JSON stringified GraphQL query. This intricate pattern fetches the collection data based on the state.collectionSlug, summoning details such as the title, description, cover image, and various statistics. It also conjures the NFT metadata for each NFT in the collection, including the image, name, token ID, rarity, ranking, owner, and list price:

body: JSON.stringify({
  query: `
    query MyQuery {
  near {
    collection(where: {slug: {_eq: "${state.collectionSlug}"}}) {
      // ... (rest of the query)
    }
  }
}`,
}),

As the data materializes before your eyes, you scrutinize the response for validity and extract the essence of the collection data and NFT metadata:


if (response) {
  const data = response;
  const collectionData = data.body.data.near.collection[0];
  let nftData = collectionData.nft_metas;

Before reshaping the state, you harmonize the NFTs by sorting them based on their list price (lowest to highest) and list status. With the finesse of an artist, you compare the list prices of each NFT and arrange them accordingly:

nftData.sort((a, b) => {
  const aListed = a.nft_state_lists && a.nft_state_lists[0];
  const bListed = b.nft_state_lists && b.nft_state_lists[0];

  if (aListed && bListed) {
    return aListed.list_price - bListed.list_price;
  } else if (aListed) {
    return -1;
  } else if (bListed) {
    return 1;
  } else {
    return 0;
  }
});

Finally, as you gaze upon the collection data and NFT data, the unseen fruits of your labor, you update the state with the acquired knowledge:

console.log(collectionData, nftData);
	State.update({ collectionData, nftData });
}

You have now successfully cast the fetchData spell, harnessing the power of the Indexer API to retrieve the NFT collection data and artfully sort the NFTs according to their list price and status

Step Three: Craft the Input Handlers and Button Click Handler

Picture yourself as a skilled puppeteer, deftly crafting input handlers to breathe life into your creation. With a gentle touch, you update the inputCollectionSlug state property, and with a flourish, you animate the button click handler to fetch the NFTs using the fetchData function.

const updateInputCollectionSlug = (e) => {
  State.update({ inputCollectionSlug: e.target.value });
};

In the first act, you guide the user's hand as they enter the collection slug, gently updating the state to reflect their input. Like a whisper on the wind, the inputCollectionSlug state property morphs to match the value entered by the user.

const handleFetchButtonClick = () => {
  State.update({ collectionSlug: state.inputCollectionSlug });
  fetchData();
};

As the second act unfolds, your creation springs into action. When the user clicks the button, your handler summons the fetchData function, setting the stage for a magical display of NFT collection data. By updating the collectionSlug state property with the inputCollectionSlug, you ensure the user's query is the star of the show.

With the elegance of a dancer and the precision of a surgeon, you've successfully crafted the input handlers and button click handler, orchestrating a symphony of interaction that brings your NFT collection explorer to life.

The Grand Finale: Render the Application

With a final flourish, render the application using React. The enchanting interface includes:

  • A form for entering the collection slug and a button to fetch the NFTs
  • A section displaying the collection's bewitching details (title, description, cover image, and statistics)
  • A gallery of NFTs from the fetched collection, showcasing their images, names, token IDs, rarities, rankings, owners, and list prices
return (
  <div
    style={{
      // ... (rest of the UI)
    }}
  >
    // ... (rest of the UI)
  </div>
);

🔗 See full source code here

A Magical Conclusion

With a flourish of digital magic, we have successfully built an NFT collection explorer using the Indexer API. Users can now enter a collection slug, unveil the details of the collection, and wander through the NFTs in a visually captivating and informative gallery. This spellbinding application showcases the power and flexibility of the Indexer API for fetching and working with NFT collection data.

Feel free to further customize the application, add more enchanting features, or integrate it into your existing magical projects. Happy coding, and may your adventures be filled with wonder!