Skip to content

How to Run Multiple Queries in Gatsby

Gatsby/

To run multiple queries in Gatsby, you can use GraphQL aliases.

To create an alias, you need to place a name of your query before the data type.

export const query = graphql`
  query IndexPageQuery {
    siteData: site {
      siteMetadata {
        description
        title
      }
    }
    latestPosts: allMarkdownRemark(limit: 10) {
      nodes {
        id
        frontmatter {
          title
          publishedAt
        }
      }
    }
    bestPost: markdownRemark(
      frontmatter: {title: {eq: "How to Add a Favicon to a Gatsby Site"}}
    ) {
      id
      frontmatter {
        title
      }
    }
  }
`;

This query creates three properties inside the data prop of your component. These properties have the same names you specified as aliases.

Extract the data by accessing data prop properties.

const IndexPage = ({ data }) => {
  const latestPosts = data.latestPosts.nodes;
  const bestPost = data.bestPost.frontmatter;
  const metadata = data.siteData.siteMetadata;
};

You can also use GraphQL aliases in static queries. And, you can use aliases to run multiple queries on the same data type.

const Header = () => {
  const data = useStaticQuery(graphql`
    query HeaderQuery {
      metadata: site {
        siteMetadata {
          title
        }
      }
      moreMetadata: site {
        siteMetadata {
          description
        }
      }
    }
  `);

  const title = data.metadata.siteMetadata.title;
  const description = data.moreMetadata.siteMetadata.description;
};