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 cor…


This content originally appeared on DEV Community and was authored by jennifertrin

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 };

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
        }
    }

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
        }
    }`
      }),
    }),

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; 

Wrapping Up

You returned the const the contained the fetch call.

}, []);
  return [unlock];
}

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

export { useUnlock };

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 };

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 };

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


This content originally appeared on DEV Community and was authored by jennifertrin


Print Share Comment Cite Upload Translate Updates
APA

jennifertrin | Sciencx (2021-08-17T20:02:42+00:00) How to access data from a subgraph on The Graph. Retrieved from https://www.scien.cx/2021/08/17/how-to-access-data-from-a-subgraph-on-the-graph/

MLA
" » How to access data from a subgraph on The Graph." jennifertrin | Sciencx - Tuesday August 17, 2021, https://www.scien.cx/2021/08/17/how-to-access-data-from-a-subgraph-on-the-graph/
HARVARD
jennifertrin | Sciencx Tuesday August 17, 2021 » How to access data from a subgraph on The Graph., viewed ,<https://www.scien.cx/2021/08/17/how-to-access-data-from-a-subgraph-on-the-graph/>
VANCOUVER
jennifertrin | Sciencx - » How to access data from a subgraph on The Graph. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/17/how-to-access-data-from-a-subgraph-on-the-graph/
CHICAGO
" » How to access data from a subgraph on The Graph." jennifertrin | Sciencx - Accessed . https://www.scien.cx/2021/08/17/how-to-access-data-from-a-subgraph-on-the-graph/
IEEE
" » How to access data from a subgraph on The Graph." jennifertrin | Sciencx [Online]. Available: https://www.scien.cx/2021/08/17/how-to-access-data-from-a-subgraph-on-the-graph/. [Accessed: ]
rf:citation
» How to access data from a subgraph on The Graph | jennifertrin | Sciencx | https://www.scien.cx/2021/08/17/how-to-access-data-from-a-subgraph-on-the-graph/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.