Federico Resnizky
Federico Resnizky

Reputation: 71

Getting data from Netlify CMS to Gatsby JS

I'm creating a site using Netlify CMS + Gatsby. I already have the site structure and some data in Netlify, but I'm having some issues getting the data into Gatsby. This is what I've got so far

import React from 'react'

export default class IndexPage extends React.Component {
  render({data}) {
    const { edges: posts } = data.allMarkdownRemark

    return (
      <section className="section">
        <div className="container">
          <div className="content">
            <h1 className="has-text-weight-bold is-size-2"></h1>
          </div>
        </div>
      </section>
    )
  }
}

export const pageQuery = graphql`
  query IndexQuery {
    allMarkdownRemark(filter: {frontmatter: {templateKey: {regex: "/home-page|media-page/"}}}) {
      edges {
        node {
          excerpt(pruneLength: 400)
          id
          fields {
            slug
          }
          frontmatter {
            title
            templateKey
          }
        }
      }
    }
  }
`

And I'm getting TypeError: Cannot read property 'data' of undefined

Upvotes: 1

Views: 480

Answers (2)

coreyward
coreyward

Reputation: 80041

This syntax is destructuring:

render({ data })

That's similar to doing this:

render(props) {
  data = props.data
}

The issue you're experiencing is that render doesn't receive any arguments/props.

The solution is to use this.props, as recommended by @talves' answer.

Upvotes: 0

talves
talves

Reputation: 14353

The props are not passed into the render as arguments.

Try:

import React from 'react'

export default class IndexPage extends React.Component {
  render() {
    const { edges: posts } = this.props.data.allMarkdownRemark

    return (
      <section className="section">
        <div className="container">
          <div className="content">
            <h1 className="has-text-weight-bold is-size-2"></h1>
          </div>
        </div>
      </section>
    )
  }
}

export const pageQuery = graphql`
  query IndexQuery {
    allMarkdownRemark(filter: {frontmatter: {templateKey: {regex: "/home-page|media-page/"}}}) {
      edges {
        node {
          excerpt(pruneLength: 400)
          id
          fields {
            slug
          }
          frontmatter {
            title
            templateKey
          }
        }
      }
    }
  }
`

Upvotes: 2

Related Questions