Search code examples
reactjsgatsbycontentful

TypeError: Cannot read property 'image' of undefined - React & Gatsby


I'm currently trying to pull some data from Contentful in my react app and keep getting this TypeError: Cannot read property 'image' of undefined.

Can't seem to see why I'm getting that.

Here is my query component - just trying to pull in the filename:

import React from 'react'
import { StaticQuery, graphql } from 'gatsby'

export default () => (
  <StaticQuery
    query={graphql`
      query FileQuery {
        allContentfulImage {
          edges {
            node {
              image {
                file {
                  fileName
                }
              }
            }
          }
        }
      }
    `}
    render={data => (
      <div>
        <h1>{data.allContentfulImage.edges.node.image.file.fileName}</h1>
      </div>
    )}
  />
)

Solution

  • data.allContentfulImage.edges contains an array of objects instead of being an object. You can try:

    <h1>{data.allContentfulImage.edges[0].node.image.file.fileName}</h1>