Lewis Menelaws
Lewis Menelaws

Reputation: 1186

Gatsby GraphQL error: Variable "$slug" is never used in operation "BlogPostQuery"

I am unable to pull in the data of my Ghost blog using Gatsby. I am using Ghost as my back end and I am using a package to get the Ghost blog as a source. The problem is just getting the individual posts on the page. Here is blog-post.js:

import React from "react";

export default ({ data }) => {
//   const post = data.allGhostPost.edges;
  return (
    <div>
      {/* <h1>{post.title}</h1> */}
      {/* <div dangerouslySetInnerHTML={{ __html: post.html }} /> */}
    </div>
  );
};

export const query = graphql`
  query BlogPostQuery($slug: String!) {
    allGhostPost {
        edges {
          node {
            id
            slug
            title
            html
            published_at
          }
        }
      }
  }
`;

Here is my gatsby node file:

exports.createPages = ({ graphql, boundActionCreators}) => {
    const {createPage} = boundActionCreators

    return new Promise((resolve, reject) => {
        const blogPostTemplate = path.resolve(`src/templates/blog-post.js`)

        resolve(
            graphql(
                `
                {
                    allGhostPost(sort: { order: DESC, fields: [published_at] }) {
                      edges {
                        node {
                          id
                          slug
                          title
                          html
                          published_at      
                        }
                      }
                    }
                  }
                `
            )
            .then(result => {
                result.data.allGhostPost.edges.forEach(edge => {
                    createPage({
                        path: edge.node.slug,
                        component: blogPostTemplate,
                        context: {
                            slug: edge.node.slug
                        }
                    })
                })
                return;
            })
        )
    })
}

Upvotes: 2

Views: 5642

Answers (1)

Lewis Menelaws
Lewis Menelaws

Reputation: 1186

I figured out my problem and it was a problem with my Queries. For anyone working with the Ghost API. This is the answer you will need:

query BlogPostQuery($slug: String!) {
  allGhostPost(filter: {slug: {eq: $slug}}) {
    edges {
      node {
        id
        slug
        title
        html
        published_at
      }
    }
  }
}

Let me explain my answer.

The issue was that my GraphQL query was not working because the $slug field was not being used within the query. It was just being passed in. That being said, I had to learn a bit of GraphQL to get to my final conclusion.

Using the GraphiQL I was able to find that the allGhostPost had a filter method. Using that I was able to pull in the right result.

Upvotes: 6

Related Questions