When looking at the gatsby-starter-blog template, it seems we're doing 2 GraphQL queries to create pages for blog posts. I don't understand why.
In gatsby-node.js we're querying for all blog posts. Then we're passing information on to the blog-post.js template. In that file a second GraphQL query is being run. Why does this happen? Couldn't we just pass all the relevant data, including the HTML, to the template component through the pageContext?
All we'd need to do is to change the query in gatsby-node.js to:
{
allMarkdownRemark(sort: {fields: [frontmatter___date], order: DESC}, limit: 1000) {
edges {
node {
id
excerpt(pruneLength: 160)
html
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
description
}
fields {
slug
}
frontmatter {
title
}
}
}
}
}
And then pass on the relevant pieces of data to the context in the createPage() function.
Am I missing something here?
I guess one of the benefit would be hot reloading. If your data requirement changes, you can modify the queries in the page template and hot reload just works. On the other hand, you need to restart dev server if you modify queries in gatsby-node.
In gatsby-node.js we're querying for all blog posts. Then we're passing information on to the blog-post.js template. In that file a second GraphQL query is being run. Why does this happen? Couldn't we just pass all the relevant data, including the HTML, to the template component through the pageContext?
@DandyDev You can definitely pass in all necessary data from gatsby-node.js (even object literals if you're not using GraphQL) but the convention is to _colocate_ data required on a page with the code for that page. This helps because it's more obvious what data is being _pulled_ in for a page once you have a lot of pages.
Also like @universse correctly mentioned, I don't think HMR will work in the proposed case.
Yeah, colocation and HMR make it very easy to iterate on adding/removing queries and changing components. Gatsby optimizes for developer speed and happiness and it's far nicer to have the query inside the component.
So to summarize:
Thanks for the help folks! Clarifies a lot for me.
Most helpful comment
So to summarize:
Thanks for the help folks! Clarifies a lot for me.