Gatsby: GraphQL query with variable

Created on 15 Nov 2017  Â·  9Comments  Â·  Source: gatsbyjs/gatsby

I've been stuck on this for a while and cannot see what is wrong, any pointers most welcome.

In short I am trying to create some pages from some data returned from prismic.
Following the guidelines in part four of the tutorial I have this in gatsby-node.js.

//create slugs
 exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {

    const { createNodeField } = boundActionCreators
    if (node.internal.owner === 'gatsby-source-prismic' && node.type === `article`) {
      const slug = `${node.slugs[0]}`;
      console.log(`slug is: ${slug}`);
      createNodeField({
        node,
        name: `slug`,
        value: slug,
      })
    }
  }

And this

exports.createPages = ({ graphql, boundActionCreators }) => {
    const { createPage } = boundActionCreators

    return new Promise((resolve, reject) => {
      const articleTemplate = path.resolve(`src/templates/article.js`)

      // Query for article nodes to use in creating pages.
      resolve(
        graphql(
          `
               {
          articles: allPrismicDocument(filter: { type: { eq: "article" } }) {
            edges {
                node {
                  fields {
                       slug
                  }
                  type
                }
              }
          }
        }
      `
        ).then(result => {
          if (result.errors) {
            reject(result.errors)
          }

          // Create pages for each article.
          result.data.articles.edges.forEach(({ node }) => {
            console.log(`create page for ${node.fields.slug}`);
            createPage({
              path: node.fields.slug,
              component: articleTemplate,
              layout: `index`,
              context: {
                slug: node.fields.slug
              }
            })
          })
          resolve()
        })
      )
    })
  }

This works as expected. Now in my template I have this.

import React from "react";

export default ({ data }) => {

    debugger;
    console.log(data);

    return (
        <section>
        </section>
    )
}

export const query = graphql`
query ArticleQuery {
    allPrismicDocument(filter: { type: { eq: "article" } }) {
        edges {

            node {
                type
                fields {
                    slug
                }
                id
                data {
                    title {
                        text
                    }
                    content {
                        text
                    }
                    slideshow {
                        photo {
                            url
                        }
                    }
                }
            }
        }
    }
}
`

This also works (as in, data is defined) BUT this was just to prove the query works. Since here I have queried by type and will of course return all articles, and not just the one that matches the slug.

But now, if I update the query to filter by the slug....

export const query = graphql`
query ArticleQuery($slug: String!) {
    allPrismicDocument(fields: { slug: { eq: $slug } }) {
        edges {

            node {
                type
                fields {
                    slug
                }
                id
                data {
                    title {
                        text
                    }
                    content {
                        text
                    }
                    slideshow {
                        photo {
                            url
                        }
                    }
                }
            }
        }
    }
}
`

Then I get a build time GraphQL compilation error.

GraphQL Error There was an error while compiling your site's GraphQL queries.

I cannot see what is wrong. I've tried several formats for the query and none compile.
Also, the query is exactly the same as in the tutorial, which does work on my machine.

Any suggestions where to start looking?
Oh and is this the best place to ask this kind of question?

Most helpful comment

    query MyFilesQuery($slug: String!) {
        allFile(filter: {
          sourceInstanceName:{
            eq:$slug
          }
        }) {
            edges {
                node {
                    relativePath
                    prettySize
                    extension
                    birthTime(fromNow: true)
                }
            }
        }
    }   

This code works for me.

All 9 comments

Could you try upgrading to the latest version of gatsby? There were a couple PRs lately which made that error more expressive — could you post the error message after you upgrade?

Nice, that should help in future. This is what I get.

GraphQL Error There was an error while compiling your site's GraphQL queries.
Invariant Violation: GraphQLParser: Unknown argument fields. Source: document ArticleQuery file: GraphQL request.

oh right, with an all* entry object, you need to add "filter" first. Your query will work if you change allPrismicDocument to prismicDocument.

BTW, highly recommend getting very familiar with Graphiql if you're not already — you can copy queries into it and play around with its autocomplete to understand what you're supposed to do.

Yeah, I do need to get more familiar with GraphQL, this is the first time I've used it.
Thanks for the pointer, after a bit of playing around in GraphiQL I've got it compiling.
Key was to update to prismicDocument, (and not data:prismicDocument and to remove edges, and node from the query.
Cheers!

query ArticleQuery($slug: String!) {
{
 prismicDocument(fields: { slug: { eq: $slug } }) {          
                type
                fields {
                    slug
                }
                id
                data {
                    title {
                        text
                    }
                    content {
                        text
                    }
                    slideshow {
                        photo {
                            url
                        }
                    }
                }
            }         
      }
}  

Oh. Appears I spoke to soon. The above query was only returning data as it was cached.
If I remove the json from the cache and restart the development server, it returns no data. I.e. the cache contains {}.

If update the query and manually include my slug, the query works and cache is populated again.

query ArticleQuery {
    prismicDocument(fields: { slug: { eq: "my-slug" } }) {

                        type
                        fields {
                            slug
                        }
                        id
                        data {
                            title {
                                text
                            }
                            content {
                                text
                            }
                            slideshow {
                                photo {
                                    url
                                }
                            }
                        }
                    }
}

Hmmm, it just started working this morning. Not sure what has changed. Gatsby development server has been stopped and started (in fact my machine has too as this issue spanned a couple of days). I did delete my cache, trying to debug another issue. I seem to run into this type of issue a lot. Probably just me not understanding something, but will keep an eye on it.

I've switched to gatsby from next.js and start to regret it a bit. It's like 6 hours now I'm fighting exactly this issue. I'm having query like

export const pageQuery = graphql`
  query TestQuery {
    works: allMarkdownRemark(filter: { fields: { contentType: { eq: "work" } } }) {
      edges {
        node {
          html
        }
      }
    }
  }
`;

and if I change even name of the query, my server crashes.

    query MyFilesQuery($slug: String!) {
        allFile(filter: {
          sourceInstanceName:{
            eq:$slug
          }
        }) {
            edges {
                node {
                    relativePath
                    prettySize
                    extension
                    birthTime(fromNow: true)
                }
            }
        }
    }   

This code works for me.

Due to the high volume of issues, we're closing out older ones without recent activity. Please open a new issue if you need help!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Oppenheimer1 picture Oppenheimer1  Â·  3Comments

kalinchernev picture kalinchernev  Â·  3Comments

KyleAMathews picture KyleAMathews  Â·  3Comments

3CordGuy picture 3CordGuy  Â·  3Comments

ferMartz picture ferMartz  Â·  3Comments