Jordan Baron
Jordan Baron

Reputation: 35

Gatsby result from useStaticQuery is undefined

I have a variable that stores the results from a useStaticQuery call but when I console.log it, it's undefined. The query works fine in GraphiQL, so why isn't it working with useStaticQuery?

const {backgroundImages} = useStaticQuery(graphql`
    query {
      allFile(
        filter: {extension: {regex: "/(png)/"}, relativeDirectory: {eq: "slider"}}
      ) {
        edges {
          node {
            base
            childImageSharp {
              gatsbyImageData(width: 10, quality: 10, webpOptions: {quality: 70})
              
            }
          }
        }
      }
    }
  `)
console.log(backgroundImages) // undefined

Upvotes: 1

Views: 413

Answers (1)

Marco Daniel
Marco Daniel

Reputation: 5765

The issue is because you're destructuring the result and asking for the key backgroundImages that does not exist on the result of your query.

This query would return a result similar to:

{
  "data": {
    "allFile": {
      "edges": [
        "node": .....
      ]
    }
  }
}

That means you cannot access the object backgroundImages by destructuring ({...}), but you can access data. If you try:

const {data} = useStaticQuery(graphql`
    query {
      ...
    }
  `)
console.log(data)

You should be able to see the log for the query.

Upvotes: 2

Related Questions