DEV Community

Jennifer K. Tran
Jennifer K. Tran

Posted on

How to access data from a subgraph on The Graph

This article outlines how to access data from a subgraph or API created on The Graph, as well as how to combine subgraph results using a React hook.

What is The Graph?

The Graph is an indexing protocol for querying networks. One of its core features is that anyone can use The Graph to build APIs of smart contract data.

Our Use Case

MintGate is a platform that allows creators and communities to set up gated videos and web content using NFTs or social tokens. Unlock Protocol is an open source, blockchain-based protocol that allows anyone to create membership, time-based NFTs.

A MintGate and Unlock Protocol integration would allow creators and communities to require an end fan to purchase an NFT to access content for a certain period of time. In our UI, we needed to detect if a user set up gated content using an NFT smart contract created on Unlock Protocol.

Development

Using Unlock Protocol's subgraphs on The Graph

We utilized Unlock Protocol's subgraphs on The Graph to get the contract addresses of all "locks" or NFT collections created using the protocol. You can view all of Unlock Protocol's subgraph information in their docs.

Step One

We created a new Javascript file and wrapped a React UseAsync hook in a const.

import { useAsync } from 'react-use';

const useUnlock = () => {
    const unlock = useAsync(async () => {
    }
}

export { useUnlock };
Enter fullscreen mode Exit fullscreen mode

Step Two

We analyzed the subgraphs and outlined how to structure the fetch call.

Here's link to the Unlock Protocol mainnet subgraph on The Graph: https://thegraph.com/legacy-explorer/subgraph/unlock-protocol/unlock.

Notes on subgraphs:

  1. The fetch API URL is the API link under "Queries (HTTP)".

Pointing to API URL on The Graph

  1. Subgraphs are POST APIs.
  2. In The Graph Playground, under Example Query box, there are examples of a request body.

Example of a Request Body

  1. In The Graph Playground, under the Schema, it lists the entries that you can index in the API. Schema

Step Three

Now that we analyzed the subgraph, we constructed our fetch call.

For us, since we wanted to get the lock or NFT collection name, we used this request body:

query {
        locks {
          address
          name
        }
    }
Enter fullscreen mode Exit fullscreen mode

Our params are as follows:

const result = await fetch(`https://api.thegraph.com/subgraphs/name/unlock-protocol/unlock`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        query: `
      query {
        locks {
          address
          name
        }
    }`
      }),
    }),
Enter fullscreen mode Exit fullscreen mode

Step Four

After we set up the params, we set up returning the result of the API.

We added this to the end of const containing the params:

then((res) => res.json());
    return result; 
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

You returned the const the contained the fetch call.

}, []);
  return [unlock];
}
Enter fullscreen mode Exit fullscreen mode

And exported the const the wraps around the entire React hook.

export { useUnlock };
Enter fullscreen mode Exit fullscreen mode

Our end result looked something similar to this:

import { useAsync } from 'react-use';

const useUnlockMainnet = () => {
  const unlockMainnet = useAsync(async () => {
    const result = await fetch(`https://api.thegraph.com/subgraphs/name/unlock-protocol/unlock`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        query: `
      query {
        locks {
          address
        }
    }
  }`
      }),
    }).then((res) => res.json());
    return result;
  }, []);
  return [unlockMainnet];
}

export { useUnlockMainnet };
Enter fullscreen mode Exit fullscreen mode

Bonus Points: How to call multiple subgraph results

In addition, we needed a way to check if a user gated content using an Unlock Protocol lock or smart contract on other chains besides Ethereum mainnet.

We needed to utilize the subgraphs on xDai and Polygon.

Using Promise.All, you fetched all of the responses and had them return in an array. Here was our end result:

import { useAsync } from 'react-use';

const useUnlock = () => {
  const unlock = useAsync(async () => {
    const result = await Promise.all([await fetch(`https://api.thegraph.com/subgraphs/name/unlock-protocol/unlock`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        query: `
      query {
        locks {
          address
          name
        }
    }`
      }),
    }),
    await fetch(`https://api.thegraph.com/subgraphs/name/unlock-protocol/xdai
      `, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        query: `
        query {
          locks {
            address
            name
          }
      }`
      }),
    }),
    await fetch(`https://api.thegraph.com/subgraphs/name/unlock-protocol/polygon
      `, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        query: `
        query {
          locks {
            address
            name
          }
      }`
      }),
    })]);
    const data = await Promise.all(result.map(res => res.json()))
    return data;
  }, []);
  return [unlock];
}

export { useUnlock };
Enter fullscreen mode Exit fullscreen mode

You can try to create an Unlock lock and set up token gated content on MintGate today!

Top comments (2)

Collapse
 
davidlaytonuk profile image
David Layton

Great stuff! Any idea of the stats for the lag in the sync between the subgraph and the chain? Also, from a UX prespective how are you handling the lag between the user signing the transaction and it being commited to the blockchain and thus appearing in the results?

Collapse
 
julien51 profile image
Julien Genestoux

Very cool! Thanks Jennifer!