How to access data from a subgraph on The Graph
Tags: react, graphql, javascript
Published: 2021-08-17 20:02:42

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?

<a href="https://thegraph.com/">The Graph</a> 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
<a href="https://www.mintgate.io">MintGate</a> is a platform that allows creators and communities to set up gated videos and web content using NFTs or social tokens. <a href="https://unlock-protocol.com/">Unlock Protocol</a> 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 <a href="https://docs.unlock-protocol.com/developers/subgraph">docs</a>. 

#### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtn2nfayu3rgrv7hc6ds.jpg)

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

![Example of a Request Body](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gg7eci64vf8yhoajiwuq.PNG)

4. In The Graph Playground, under the Schema, it lists the entries that you can index in the API.
![Schema](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2zotyguevygqdpsxz2uw.PNG)

#### 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 <a href="https://thegraph.com/legacy-explorer/subgraph/unlock-protocol/xdai">xDai</a> and <a href="https://thegraph.com/legacy-explorer/subgraph/unlock-protocol/polygon">Polygon</a>.

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!