Search code examples
graphqlgatsbycontentful

How can I filter data fetched from Contentful using a value also fetched from Contentful in Gatsby?


I am trying to fetch data from Contentful with a filter whose eq operator is also fetched from Contentful. In my current scenario, as shown in the code below, I am trying to filter the content fetched from allContentfulPost with the value fetched from label in contentfulCategory.

Any ideas how I can do so? I tried using $label in the allContentfulPost filter eq operator, but that didn't work.

export const pageQuery = graphql`

  query CategoryBySlug($slug: String!) {

    contentfulCategory (slug: { eq: $slug }) {
      slug
      label
    }

    allContentfulPost (filter: { categories: { elemMatch: { label: { eq: ????? } } } }) {
      edges {
        node {
          title
          slug
          featured
          image {
            fluid {
              src
            }
          }
        }
      }
    }
  }
`

Solution

  • Contentful DevRel here. 👋

    Can you try the following query? :)

    export const pageQuery = graphql`
      query CategoryBySlug($slug: String!) {
        contentfulCategory (slug: { eq: $slug }) {
          slug
          label
        }
    
        allContentfulPost (filter: { 
          categories: { 
            elemMatch: { 
              slug: { 
                # 👇 reuse the $slug argument to filter the related articles 
                eq: $slug
              }
            }
          }
        }) {
          edges {
            node {
              title
              slug
              featured
              image {
                fluid {
                  src
                }
              }
            }
          }
        }
      }
    `
    

    You can filter for $slug in allContentfulPost, too. With the query above you're requesting two different resources:

    1. the one category matching the $slug as contentfulCategory

    2. posts that are linking to a category that matched the correct $slug as allContentfulPost