question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[v2] Using a variable for the `query` prop of the `StaticQuery` component won't work

See original GitHub issue

Description

If I try to assign my GraphQL to a variable as a const, and then pass it to my query prop of my <SaticQuery/> component, I only get “Loading (StaticQuery)” rendered on my page.

Steps to reproduce

In your functional layout component assign, inside your <SaticQuery/>, your GraphQL query to a const like:

const Layout = ({ children }) => {
    const layoutQuery = graphql`
        query SiteTitleQuery {
            site {
                siteMetadata {
                    title
                }
            }
        }
    `
    return (
    <StaticQuery
        query={layoutQuery}
        … // something else
    />
    )
}

Expected result

I expected to get the const variable parsed as a normal GraphQL query getting, then, a rendered page.

Actual result

I only got a white page with the words “Loading (StaticQuery)” on it (no errors in console).

Environment

System: OS: macOS High Sierra 10.13.6 CPU: x64 Intel® Core™ i5-7360U CPU @ 2.30GHz Shell: 5.3 - /bin/zsh Binaries: Node: 8.11.3 - ~/.nvm/versions/node/v8.11.3/bin/node npm: 6.1.0 - ~/.nvm/versions/node/v8.11.3/bin/npm Browsers: Chrome: 67.0.3396.99 Safari: 11.1.2 npmPackages: gatsby: next => 2.0.0-beta.46 gatsby-image: next => 2.0.0-beta.6 gatsby-plugin-react-helmet: next => 3.0.0-beta.3 gatsby-plugin-sass: next => 2.0.0-beta.5 gatsby-plugin-sharp: next => 2.0.0-beta.5 gatsby-source-filesystem: next => 2.0.1-beta.6 gatsby-transformer-remark: next => 2.1.1-beta.3 npmGlobalPackages: gatsby: 2.0.0-beta.46

File contents (if changed)

gatsby-config.js:

module.exports = {
    siteMetadata: {
        title: 'Gatsby Default Starter',
    },
    plugins: [
        `gatsby-plugin-react-helmet`,
        {
            resolve: `gatsby-source-filesystem`,
            options: {
                path: `${__dirname}/src/posts`,
                name: `posts`,
            },
        },
        `gatsby-transformer-remark`,
        `gatsby-plugin-sass`
    ],
}

package.json:

{
    "name": "carusog",
    "description": "Giuseppe Caruso personal blog",
    "version": "1.0.0",
    "author": "Giuseppe Caruso <myemail@example.com>",
    "dependencies": {
        "gatsby": "next",
        "gatsby-image": "next",
        "gatsby-plugin-react-helmet": "next",
        "gatsby-plugin-sass": "next",
        "gatsby-plugin-sharp": "next",
        "gatsby-source-filesystem": "next",
        "gatsby-transformer-remark": "next",
        "node-sass": "^4.9.2",
        "react": "^16.4.1",
        "react-dom": "^16.4.1",
        "react-helmet": "^5.2.0"
    },
    "keywords": [
        "gatsby"
    ],
    "license": "MIT",
    "scripts": {
        "build": "gatsby build",
        "develop": "gatsby develop",
        "format": "prettier --write 'src/**/*.js'",
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "devDependencies": {
        "prettier": "^1.12.0"
    }
}

gatsby-node.js:

/**
 * Implement Gatsby's Node APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/node-apis/
 */

const path = require('path')

exports.createPages = ({ actions, graphql }) => {
    const { createPage } = actions
    const blogPostTemplate = path.resolve(`src/templates/blog-post.js`)

    return graphql(`
        {
            allMarkdownRemark(
                sort: { order: DESC, fields: [frontmatter___date] },
                limit: 10
            ) {
                edges {
                    node {
                        html
                        id
                        frontmatter {
                            title
                            date
                            path
                            excerpt
                            tags
                        }
                    }
                }
            }
        }
    `)
    .then(result => {
        if (result.errors) {
            return Promise.reject(result.errors)
        }

        const posts = result.data.allMarkdownRemark.edges

        posts.forEach(({ node }, index) => {
            createPage({
                path: node.frontmatter.path,
                component: blogPostTemplate,
                context: {
                    // prev and next seem inverted but we must consider that being posts sorted
                    // by date, DESC, last one is actually first post and vice versa
                    next: index === 0 ? null : posts[index - 1].node,
                    prev: index === (posts.length - 1) ? null : posts[index + 1].node
                }
            })
        });
    })
}

gatsby-browser.js: N/A gatsby-ssr.js: N/A

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:11
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
gabrielbullcommented, Aug 15, 2018

Just a note that relay can pass the query from file to file without any issues.

We can expect people will want to write HOC to wrap the StaticQuery into a more usable function and we cannot do that unless the query can be passed around as a variable.

1reaction
KyleAMathewscommented, Jul 20, 2018

Yeah, we should support pulling in a query defined in the same file — it shouldn’t be too hard I don’t think… if someone with some Babel experience wants to tackle it.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Querying Data in Components using StaticQuery - Gatsby
By using StaticQuery , you can colocate a component with its data. It is no longer required to, say, pass data down from...
Read more >
How to use variables in components with Gatsby Graphql
To use variables in page queries, you need to provide them using context, not via props as you were trying to when you...
Read more >
Gatsby: Fetching Data at The Component Level with ...
Now, here's how to take that query out of the parent and modularize it for the new world of React Hooks. Gatsby v2...
Read more >
Static Queries - How to Gatsby: The Complete Course
Previously, this was done with the StaticQuery component that accepts a query prop for the query, and a render prop for the JSX...
Read more >
Gatsby useStaticQuery Hook: The Quick Guide
However, Gatsby V2 introduced a staticQuery API that allows data to ... we can run multiple queries using GraphQl aliases inside components.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found