Me Articles

How to filter sites using allSitePage with Gatsby and GraphQL

Honestly, I've been using NextJS for the last couple of years. But there still is, one thing I really miss from using Gatsby. It's all about fetching the pages generated in gatsby-node.js.
I still haven't found a way as effective as this, in NextJS. Let's have a look using Gatsby, and sorting different types to each different category page.

[
  {
    title: "Cola",
    category: "drink",
  },
  {
    title: "Fanta",
    category: "drink",
  },
  {
    title: "Cake",
    category: "dessert",
  },
  {
    title: "Icecream",
    category: "dessert",
  },
]


Have a look at this tiny API.
Now if these pages are built from a REST API, we can fetch them A LOT faster, using GraphQL and get all generated pages.

const data = useStaticQuery(graphql`
      {
        allSitePage {
          edges {
            node {
              path
              context {
                title
                category
              }
            }
          }
        }
      }
    `)


There you go. Easy as that and you will now have all pages. This is very useful, if you are generating pages from REST API, and don't have to fetch them once again.

We can even filter pages. Let's say we only want products from the category "dessert".

const data = useStaticQuery(graphql`
      {
        allSitePage(
          filter: {
            context: {
              category: { eq: "dessert" }
            }
          }
        ) {
          edges {
            node {
              path
              context {
                title
              }
            }
          }
        }
      }
    `)


This is probably the only thing I really miss using NextJS. I know that there are workarounds in NextJS, but not nearly as effective and simple as this.

Me Articles How to filter sites using allSitePage with Gatsby and GraphQL