简体   繁体   中英

Gatsby & Contentful Querying

I am having a hard time finding documentation that accurately depicts how to use the "gatsby-source-contentful" plugin and query data from the contentful API. I have everything set up in the gatsby-config.js file and there are no running errors. I am wondering how to start making these calls. I have looked at the /___graphql path and I don't see any query options related to contentful.

Any information would be greatly appreciated.

This is my config data for the plugin

{
   resolve: `gatsby-source-contentful`,
   options: {
     spaceId: keys.spaceId,
     accessToken: keys.accessToken,
   },
},

It seems your gatsby-config file is ok (if your accessToken is valid, no error there). Try this example query to retrieve data from Contentful:

export const pageQuery = graphql`
  query HomeQuery {
    allContentfulBlogPost(sort: { fields: [publishDate], order: DESC }) {
      edges {
        node {
          title
          slug
          publishDate(formatString: "MMMM Do, YYYY")
          tags
          heroImage {
            sizes(maxWidth: 350, maxHeight: 196, resizingBehavior: SCALE) {
             ...GatsbyContentfulSizes_tracedSVG
            }
          }
          description {
            childMarkdownRemark {
              html
            }
          }
        }
      }
    }
    allContentfulPerson(filter: { id: { eq: "c15jwOBqpxqSAOy2eOO4S0m" } }) {
      edges {
        node {
          name
          shortBio {
            shortBio
          }
          title
          heroImage: image {
            sizes(
              maxWidth: 1180
              maxHeight: 480
              resizingBehavior: PAD
              background: "rgb:000000"
            ) {
              ...GatsbyContentfulSizes_tracedSVG
            }
          }
        }
      }
    }
  }
`

Inside the page, you can access the data this way:

const siteTitle = this.props.data.site.siteMetadata.title;
const posts = this.props.data.allContentfulBlogPost.edges;
const [author] = this.props.data.allContentfulPerson.edges;

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