DEV Community

Cover image for Gatsby Tip on Running Multiple Queries (GraphQL Aliases)
Malik Gabroun
Malik Gabroun

Posted on • Edited on • Originally published at malikgabroun.com

1 2

Gatsby Tip on Running Multiple Queries (GraphQL Aliases)

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
      }
    }
  }
`;
Enter fullscreen mode Exit fullscreen mode

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
dmytro_dmytro_dmytro profile image
Dmytro Dmytro

Awesome Tip. Thanks!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs