Gatsby: How to query all categories at once?

Created on 8 Aug 2019  路  3Comments  路  Source: gatsbyjs/gatsby

Summary

I have several posts with different categories. How do I query all categories of the posts at once?

Relevant information

I have something like:

  • One.md (category is News)
  • Two.md (category is Events)
  • Three.md (category is News)
  • Four.md (category is Events)

However, when I try to query something like this:

{
  allMarkdownRemark(filter: {fileAbsolutePath: {regex: "/(/news/)/"}, frontmatter: {category: {}}}) {
    edges {
      node {
        frontmatter {
          category
        }
      }
    }
  }
}

It will return:

{
  "data": {
    "allMarkdownRemark": {
      "edges": [
        {
          "node": {
            "frontmatter": {
              "category": "Event"
            }
          }
        },
        {
          "node": {
            "frontmatter": {
              "category": "News"
            }
          }
        },
        {
          "node": {
            "frontmatter": {
              "category": "News"
            }
          }
        },
        {
          "node": {
            "frontmatter": {
              "category": "News"
            }
          }
        }
      ]
    }
  }
}

Which I'd expect it should only return:

  • News
  • Events
question or discussion

Most helpful comment

You can use the group query:
https://www.gatsbyjs.org/docs/graphql-reference/#group

fieldValue is what you're interested in then.

All 3 comments

There's no way to query and get the category only. You can do this:

const categories = this.props.data.allMarkdownRemark.edges.map(
    ({node}) => node.frontmatter.category);

You can use the group query:
https://www.gatsbyjs.org/docs/graphql-reference/#group

fieldValue is what you're interested in then.

Thanks! the information is really helpful :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

totsteps picture totsteps  路  3Comments

kalinchernev picture kalinchernev  路  3Comments

timbrandin picture timbrandin  路  3Comments

ferMartz picture ferMartz  路  3Comments

hobochild picture hobochild  路  3Comments