gatsbyjs/gatsby-source-wordpress-experimental

Docs: Minor improvement of code recipe in 'Creating a new site from scratch' tutorial

Closed this issue · 1 comments

Hi,

In a tutorial on Creating a new site from scratch I think there's a better way to write code for blog-post.js:

import React from "react"
import Layout from "../components/layout"
import { graphql } from "gatsby"

export default function BlogPost({ data }) {
  const post = data.allWpPost.nodes[0]
  console.log(post)
  return (
    <Layout>
      <div>
        <h1>{post.title}</h1>
        <div dangerouslySetInnerHTML={{ __html: post.content }} />
      </div>
    </Layout>
  )
}
export const query = graphql`
  query($slug: String!) {
    allWpPost(filter: { slug: { eq: $slug } }) {
      nodes {
        title
        content
      }
    }
  }
`

As long as this component is called by gatsby-node.js for each page and it gets a $slug via context, there seems to be no point in querying and filtering allWpPost and then picking 0th of nodes. We can query a wpPost type to get just the one post we need, utilizing slug argument and a variable. I'd suggest writing it like this:

import React from "react"
import Layout from "../components/layout"
import { graphql } from "gatsby"

export default function BlogPost({ data }) {
- const post = data.allWpPost.nodes[0]
+ const post = data.wpPost
  console.log(post)
  return (
    <Layout>
      <div>
        <h1>{post.title}</h1>
        <div dangerouslySetInnerHTML={{ __html: post.content }} />
      </div>
    </Layout>
  )
}
export const query = graphql`
  query($slug: String!) {
-    allWpPost(filter: { slug: { eq: $slug } }) {
+    wpPost(slug: { eq: $slug } ) {
-     nodes {
        title
        content
-      }
    }
  }
`

I guess that will make the code a bit cleaner and easier to follow 😺

Good call! If you want to open a PR the starter now lives here https://github.com/gatsbyjs/gatsby-starter-wordpress-blog