简体   繁体   中英

Gatsby and GraphQL: Accessing data in a template page

I have a Gatsby project built with Gatsby-Ghost-Starter. I am trying to access blog post data from Ghost within a Gatsby template file. I'm successfully accessing some of the data, but having trouble accessing nested GraphQL data.

Using the Graphiql interface this is the data I am attempting to get:

query MyQuery {
  allGhostPost {
    edges {
      node {
        id
        slug
        tags {
          id
          slug
          meta_title
          name
        }
      }
    }
  }
}

Here is what my query looks like in my Gatsby template:

export const pageQuery = graphql`
  query GhostPostQuery($limit: Int!, $skip: Int!) {
    allGhostPost(
        sort: { order: DESC, fields: [published_at] },
        limit: $limit,
        skip: $skip
    ) {
      edges {
        node {
          ...GhostPostFields
        }
      }
    }
  }
`

Here is my Gatsby template component:

const Blog = ({ data, location, pageContext }) => {
    const posts = data.allGhostPost.edges
    const { pageNumber } = pageContext
    const { humanPageNumber } = pageContext
    const { numberOfPages } = pageContext

    // Dot notation here results in an error, how can I access the name property?
    const id = data.allGhostPost.edges.node.tags.name

    return (
        <React.Fragment>
            <MetaData location={location} />
            <Layout>
                <div className={styles.container}>
                    <section className={styles.postFeed}>
                        {posts.map(({ node }) => (
                            // The tag below includes the markup for each post - components/common/PostCard.js
                            <PostCard key={node.id} post={node} />
                        ))}
                    </section>
                    <Pagination pageContext={pageContext} />
                </div>
            </Layout>
        </React.Fragment>
    );
};
 

How can I access data nested within the edges/node objects? Is my GraphQL query incorrect or is there an issue with how I'm attempting to access it with dot notation?

For example, how can I retrieve name or meta_title ?

I'm a bit confused about what are you asking. You have a loop of posts where all the information is stored. Just access to it with:

{posts.map(({ node }, index) => {
   console.log('tag name:', node.tags[index].name)
   return <PostCard key={node.id} post={node} />
})}

Just access to nested properties in your posts .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM