Gatsby and GraphQL
Tags: gatsby, graphql, beginners, webdev
Published: 2022-01-29 15:37:59

Gatsby is a modern take on static site generator which is built on React and uses GraphQL to extract information from data sources. 

In the previous [article](https://anuradha.hashnode.dev/introduction-to-gatsby-part-1), we have learned the basics of Gatsby, let's now learn about the relation of Gatsby and GraphQL. 

![undraw_gatsbyjs_st4g.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643466115539/MlqP9RweU.png)

## 🔍 What is GraphQL?

- A query language used to query data
- Alternative to using a REST APIs
- It is one of the ways that you can import data into your Gatsby components. 
- In GraphQL queries, we do not only specify what we want, but we also specify how we want it structured in return.

If you want to learn more about GraphQL, visit [here](https://graphql.org/)

## 🔍 Why does Gatsby use GraphQL?

One of the main features of Gatsby is we can use different data sources for our website e.g. (WordPress, Shopify, Firebase, file System) and Gatsby provides the mechanism using which we can query it and access it the same way from our website using GraphQL queries. 

Gatsby basically mesh together all the data sources into a unified GraphQL layer which is also known as **Content Mesh.**

## 🔍 GraphiQL

There is a tool provided by Gatsby that makes GraphQL much easier to understand and work with. If you run `gatsby develop`, you may have noticed that there are actually two URLs to the local server once the process is complete. 

- `http://localhost:8000/`:- It goes to the live site.
- `http://localhost:8000/___graphql`:- It goes to the GraphiQL, an in-browser IDE, to explore your site's data and schema.

On this GraphiQL interface we can do the following:
- You can explore your entire GraphQL setup on your local server.
- We can craft custom requests and can directly see their results on the right-hand side.

![Screenshot from 2022-01-29 19-02-39.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643463207079/aswdJxzQY.png)
- GraphQL will return JSON objects which later you can parse like any other object in Javascript.
- Use **Code Explorer** to know how to use these queries inside your code.

![Screenshot from 2022-01-29 19-05-34.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643463359443/r2cD1fVXK.png)
- **Code Explorer** provides an option to see how to use different types of queries in your code.

![Screenshot from 2022-01-29 19-08-46.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643464950759/q9QqZ_9oc.png)

## 🔍 Types of GraphQL Queries

There are two different types of GraphQL queries which are used in two different circumstances. 
- Page Query
- Static Query

### ✏️ Page Query

- A page query sits separately from the main export component. Gatsby is going to find this query and it will return the **data** property inside our component as a prop.
- We can use **query variables**, which means we can make its query *self-dynamic* through passing variables to it.
- It only works for pages. We cannot use page queries inside a component. 

### ✏️ Static Query

- It sits inside the component itself.
- It cannot receive a variable as the name *static* suggests.
- **useStaticQuery** is a React hook available to use static query as a separate entity inside our components.

Now let's write some code to understand it better!!

## 🔍 Write GraphQL Query

Now to see how graphQL queries work, let's add some data.

### ✏️ Add Site Metadata

In the `gatsby-config.js` file, we'll store our site Metadata. 

```javascript
module.exports = {
  siteMetadata: {
    title: 'Learn Gatsby',
    description: 'step-by-step guide to learn gatsby',
    author: 'Anuradha Aggarwal',
    lang: 'en',
  },
}
```

We'll look at how to use this metadata via graphQL query in the later part.

From the previous post, we have the `Layout.js` file in the `src/components` folder.

```javascript
import React from 'react';
import Header from './Header';

export default function Layout({ children }) {
  return (
    <div className="layout">
      <Header />
      <div className="content">
        <h1>Welcome to our Gatsby Site :)</h1>
        <p>Gatsby is known as static site generator !!!</p>
        <hr />
        {/* content for each page */}
        {children}
      </div>
    </div>  )
}
```

And `about.js` in the `src/pages` folder.

```javascript
import React from 'react';
import Layout from '../components/Layout';

export default function About() {
  return (
    <Layout>
      <div>
        <h3>About page</h3>
        <p>description here</p>
      </div>
    </Layout>
  )
}
```

Now it's time to write some queries.

### ✏️ Write Page Query

As we know **Page Query** only works for pages, let's write some inside our `about.js` file.

**Step 1:  Import GraphQL**

```javascript
import { graphql } from "gatsby";
```

**Step 2: Query SiteMetadata**
```javascript
export const query = graphql`
  {
    site {
      siteMetadata {
        description
        title
      }
    }
  }
`
```
Gatsby is going to find this query and it will return the **data** property inside our component as a prop.

**Step 3: Use this query data inside your component**

```javascript
export default function About({ data }) {
  const { title, description } = data.site.siteMetadata;
  return (
    <Layout>
      <div>
        <p>{title}</p>
        <p>{description}</p>
      </div>
    </Layout>
  )
}
```

Now at the end, our `about.js` file will look like this:

```javascript
import React from 'react';
import Layout from '../components/Layout';
import { graphql } from "gatsby";

export default function About({ data }) {
  const { title, description } = data.site.siteMetadata;
  return (
    <Layout>
      <div>
        <p>{title}</p>
        <p>{description}</p>
      </div>
    </Layout>
  )
}

export const query = graphql`
  {
    site {
      siteMetadata {
        description
        title
      }
    }
  }
`
```


![Screenshot from 2022-01-29 18-15-35.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643460357919/sVQcSWTAF.png)


### ✏️ Write Static Query

Now let's see how to use Static Query.

In `Layout.js` file:

**Step 1:  Import GraphQL & useStaticQuery hook**

```javascript
import { graphql, useStaticQuery } from 'gatsby';
```

**Step 2: Query SiteMetadata**

```javascript
const data = useStaticQuery(graphql`
    query SiteInfos {
      site {
        siteMetadata {
          description
          title
        }
      }
    }
  `)
```

**Step 3: Use data in your component**

In the end, the `Layout.js` file will look like this:

```javascript
import React from 'react';
import Header from './Header';

export default function Layout({ children }) {

  const data = useStaticQuery(graphql`
    query SiteInfos {
      site {
        siteMetadata {
          description
          title
        }
      }
    }
  `)

  const { title, description } = data.site.siteMetadata

  return (
    <div className="layout">
      <Header />
      <div className="content">
        <h1>{title}</h1>
        <p>{description}</p>
        <hr />
        {/* content for each page */}
        {children}
      </div>
    </div>
  )
}
```

![Screenshot from 2022-01-29 18-26-34.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1643461015771/Jsk4vc8uA.png)

As you see GraphQL queries are almost the same in both cases, it differs in how to use it inside or outside the components which varies on your use case.
  
## 🔍 Wrap Up!!

That's all for this article. Thank you for your time!! Let's connect to learn and grow together.

[LinkedIn](https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/) [Twitter](https://twitter.com/Anuradh06359394) [Instagram](https://www.instagram.com/blogcode404/)

[![Buy-me-a-coffee](https://cdn.buymeacoffee.com/buttons/v2/default-blue.png)](https://www.buymeacoffee.com/anuradha2612)