Gatsby tip on running multiple queries (GraphQL aliases)

1 min read

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

GraphQL Alias

1
export const query = graphql`
2
query {
3
post: allMarkdownRemark(
4
limit: 3
5
sort: { order: DESC, fields: [frontmatter___date] }
6
filter: { frontmatter: { type: { ne: "portfolio" } } }
7
) {
8
edges {
9
node {
10
timeToRead
11
frontmatter {
12
title
13
path
14
date(formatString: "DD MMMM YYYY")
15
summary
16
images
17
tags
18
type
19
}
20
}
21
}
22
}
23
portfolio: allMarkdownRemark(
24
sort: { order: DESC, fields: [frontmatter___date] }
25
filter: { frontmatter: { type: { eq: "portfolio" } } }
26
) {
27
edges {
28
node {
29
frontmatter {
30
title
31
path
32
images
33
tags
34
type
35
}
36
}
37
}
38
}
39
siteMetaData: site {
40
siteMetadata {
41
title
42
}
43
}
44
}
45
`;

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