Gatsby tip on running multiple queries (GraphQL aliases)

calendar icon
15 Apr 2019
clock icon
1 min read
Gatsby tip on running multiple queries (GraphQL aliases)

Photo by Alvaro Reyes

Say you want to fetch specific data in one page based on an argument or a condition which can't be run using one query as you can't query the same field with different condition or argument. One way of doing that by using GraphQL aliases which you can use to rename the returned dataset to anything you want.

Example

export const query = graphql`
  query {
    post: allMarkdownRemark(
      limit: 3
      sort: { order: DESC, fields: [frontmatter___date] }
      filter: { frontmatter: { type: { ne: "portfolio" } } }
    ) {
      edges {
        node {
          timeToRead
          frontmatter {
            title
            path
            date(formatString: "DD MMMM YYYY")
            summary
            images
            tags
            type
          }
        }
      }
    }
    portfolio: allMarkdownRemark(
      sort: { order: DESC, fields: [frontmatter___date] }
      filter: { frontmatter: { type: { eq: "portfolio" } } }
    ) {
      edges {
        node {
          frontmatter {
            title
            path
            images
            tags
            type
          }
        }
      }
    }
    siteMetaData: site {
      siteMetadata {
        title
      }
    }
  }
`;

Looking at the above example, we can see the query I made will return multiple datasets by giving it an alias which allowed me to run multiple queries with different arguments and conditions to get the specific data object I needed as you can see in the screenshot.

graphql alias

If you found this article helpful

You will enjoy these other articles.

Gatsby useStaticQuery Hook: The Quick Guide
tag icon

#graphql

#javascript

#gatsby

Gatsby useStaticQuery Hook: The Quick Guide

In this post, we will be looking into Gatsby useStaticQuery hook, graphql aliases and custom hook.

Subscribe to the newsletter

subscribe to get my latest content, favourite articles from the web and additional details about my launches, products, and experiments