Reputation: 891
I'm testing Gatsby and GraphQl for the first time and I'm trying on a simple example....
I have this error when I want to display the title via a GraphQl request in my layout? : Uncaught TypeError: Cannot read property 'site' of undefined
here is my layout:
import React from 'react'
import { graphql } from 'gatsby'
export default ({ children, data }) =>
<div style={{margin: 'auto', maxWidth: 760}}>
<h2>{data.site.siteMetadata.title}</h2>
{children}
<footer>
Copyright blablb abolajoa.
</footer>
</div>
export const query = graphql`
query LayoutQuery {
site {
siteMetadata {
title
}
}
}
`
and my gatsby-config.js :
module.exports = {
siteMetadata: {
title: `Hardcoders`
},
plugins: [
{
resolve: 'gatsby-plugin-typography',
options: {
pathToConfigModule: 'src/utils/typography.js'
}
},
]
}
and here is the configuration of the project:
"dependencies": {
"gatsby": "^2.0.0",
"gatsby-plugin-typography": "^2.2.0",
"react": "^16.5.1",
"react-dom": "^16.5.1",
"react-typography": "^0.16.13",
"typography": "^0.16.17",
"typography-theme-github": "^0.15.10"
}
any idea what's jamming?
Upvotes: 9
Views: 5258
Reputation: 12203
In Gatsby there are 2 types of graphql queries that I am aware of, page queries and static queries.
Page Queries
These are typically included at the bottom of a component file under src/pages
folder. The query results get automatically passed to the props.data attribute of their corresponding page component.
https://www.gatsbyjs.org/docs/page-query/
Static Queries These are created using a StaticQuery component that can be included in any React component (aka. not just under src/pages folder). https://www.gatsbyjs.org/docs/static-query/
For your case it sounds like you are attempting a page query in a non-page component which will not get auto assigned to the data prop. You might try moving your query into whatever page component is consuming the Layout, or you could convert it to a static query via StaticQuery component.
e.g. in src/pages/index.jsx
export default ({ data }) => (
<Layout data={data}>
</Layout>
);
export const query = graphql`
query LayoutQuery {
site {
siteMetadata {
title
}
}
}
}
Upvotes: 23