Gatsby/GraphQL behaving differently in code from GraphiQL

77 views Asked by At

So I created a starter Gatsby site by following this:

I have some simple content on GraphCMS:

I am trying to query GraphCMS to return all the page posts. When experimenting with GraphiQL locally I use this query:

  query PageQuery {
    allGraphCmsPage {
      nodes {
        headline
        tagline
      }
    }
  }

Which returns exactly what I want

In my index.js I am querying graphCMS with this code:

const {graphCmsPage = {}} = useStaticQuery (graphql`
  query PageQuery {
    allGraphCmsPage {
      nodes {
        headline
        tagline
      }
    }
  }
`);

When I console.log it or try to reference any of the properties, they are all null/(the object being returned itself is a proto)

I am very new to GraphQL & Gatsby so I imagine I am not resolving something properly.

1

There are 1 answers

0
Ferran Buireu On BEST ANSWER

When using a page query, your data is stored under props.data object. In your case it will be:

props.data.allGraphCmsPage

The whole code should look like:

import React from 'react'
import { graphql } from 'gatsby'

 const HomePage = ({data}) => {
  console.log(data)
  return (
    <div>
      Hi!
    </div>
  )
}

export const query = graphql`
 query PageQuery {
    allGraphCmsPage {
      nodes {
        headline
        tagline
      }
    }
  }
`

export default HomePage

Keep in mind that you are using a static query (or the useStaticQuery hook) instead of a page query, what I would suggest. Check the documentation about Static vs Normal queries for further information but basically, all retrieved data in top-level components should be gathered using a page query and all the metadata and another kind of static data should be fetched using a static query, speaking generally.