Search code examples
reactjsgraphqlgatsbycontentfulgatsby-image

Cannot read property of undefined image within Gatsby, Contentful and Graphql?


I am trying to display an image stored on Contentful using Graphql within my Gatsby project.

I am using gatsby-plugin-image as gatsby-image appears to be depreciated. So far I have followed documentation online that seems to render results however when I attempt it on my local machine I am thrown an error message.

My code is as follows:

import * as React from "react"
import { Link, graphql } from "gatsby"
import { StaticImage } from "gatsby-plugin-image"
// import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import Layout from "../components/layout"
import Seo from "../components/seo"
import Navbar from "../components/Navbar"
import Img from 'gatsby-plugin-image'

function App( {data} ) {
  return (
    <>

    <Layout>
     <Img fluid={data.allContentfulHeroImage.edges.node.heroImage.fluid}></Img>
     </Layout>

    </>
  )
}

export default App;

export const query = graphql 
`query MyQuery {
  allContentfulHeroImage {
    edges {
      node {
        heroImage {
          fluid (maxWidth: 2000) {
                        ...GatsbyContentfulFluid
          }
        }
      }
    }
  }
}`

The error message reads as follows:

Cannot read property 'heroImage' of undefined

The code compiles file generating a server however throws a runtime error.

When investigating the Graphql query, it seems to be returning everything okay.

{
  "data": {
    "allContentfulHeroImage": {
      "edges": [
        {
          "node": {
            "heroImage": {
              "fluid": {
                "base64": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAMAAABI111xAAACKFBMVEX+/Pzu6ue4qp/Hw8HLzc6srK6SjoXAvbrTzcbNeobeMFTLuaj27+r69fHp39bi1cnv49b89/D9/f3+/P3u6ui3qp7HxMNsgY2SorCAgX2/vLrOx8DZU2X1EEGmiHv28e7269/z7Ob18e758ur78OL+/v62qJzEwcCLj5Ggq7OIjZK+u7uguclxfYuQgoN6kJ7v7On27ODz7+3l2db27+f88uT9+/qzppve2dbQy8nQzMnRzcm9xcssgLg/g61IhKc6h77h5ej16+Dw7OjPwb7m3tT78uWwo5jz7eny7Ofy7Oi2y9kserEZZ5oYbadTibbR2+T16t7u5+PfysX06Nz78+ft6eeuoJa0yNZCga6IpKwwfrU2hLzZ3eD17OLp3M/s4tj16Nn89OmrnpTz7efK1Nkbbqglda1TjrhBfafy7uv8+fb69/T17+nw4tP8+fT9/PymmZHs5eDc1M/Pw8C/sa2Yr78KYZ0OZ6UTbas4d6Lz7+v8+PX7+ff7+vj8/Prm5OXt6eVhUk2tmZCwnpOgi32WgnR9gYQNX5oKXJkWb6tVfpn79/T59vP6+Pb8+/ra2Np5dnesqqyEd23j39WppJljY2R2aV1ma2wOXJUWY5sYbamAh4vx7en69vP59fH69/XLyMjAvsDb2tu9trhgXWKxsLJ/cmjV1cyEhH11bGiBcWaMkZUHUIgVYpkWaKGjm5Xm3Njw6eTg2tT49PHX0tHf3d2cmZsK8zYRAAAACXBIWXMAACToAAAk6AGCYwUcAAAAB3RJTUUH5QgXDwE4TabKlAAAAGtJREFUCB1lwcERAUEQhtH/2+qjoVdvAspFBBKQhxDkIicnInBwdOyiJDBOpmrNe4iOCDqJpjVzD9n+tmUu0q44UAealMWBj6oKTaSlFuUpFRodLbRkxc/bIX04Xcbm5ZuxupwzPZv4c9/xBY2+FUzXeF9XAAAAAElFTkSuQmCC",
                "aspectRatio": 1.7702233250620347,
                "src": "//images.ctfassets.net/m7ipc0qjqa17/5H1yapaRznP5PlOxymzApj/d60687e3c7acc68a866d2718a4db125c/Screenshot_2021-08-23_145047.png?w=800&q=50",
                "srcSet": "//images.ctfassets.net/m7ipc0qjqa17/5H1yapaRznP5PlOxymzApj/d60687e3c7acc68a866d2718a4db125c/Screenshot_2021-08-23_145047.png?w=200&h=113&q=50 200w,\n//images.ctfassets.net/m7ipc0qjqa17/5H1yapaRznP5PlOxymzApj/d60687e3c7acc68a866d2718a4db125c/Screenshot_2021-08-23_145047.png?w=400&h=226&q=50 400w,\n//images.ctfassets.net/m7ipc0qjqa17/5H1yapaRznP5PlOxymzApj/d60687e3c7acc68a866d2718a4db125c/Screenshot_2021-08-23_145047.png?w=800&h=452&q=50 800w,\n//images.ctfassets.net/m7ipc0qjqa17/5H1yapaRznP5PlOxymzApj/d60687e3c7acc68a866d2718a4db125c/Screenshot_2021-08-23_145047.png?w=1200&h=678&q=50 1200w,\n//images.ctfassets.net/m7ipc0qjqa17/5H1yapaRznP5PlOxymzApj/d60687e3c7acc68a866d2718a4db125c/Screenshot_2021-08-23_145047.png?w=1600&h=904&q=50 1600w,\n//images.ctfassets.net/m7ipc0qjqa17/5H1yapaRznP5PlOxymzApj/d60687e3c7acc68a866d2718a4db125c/Screenshot_2021-08-23_145047.png?w=2400&h=1356&q=50 2400w,\n//images.ctfassets.net/m7ipc0qjqa17/5H1yapaRznP5PlOxymzApj/d60687e3c7acc68a866d2718a4db125c/Screenshot_2021-08-23_145047.png?w=3567&h=2015&q=50 3567w",
                "sizes": "(max-width: 800px) 100vw, 800px"
              }
            }
          }
        }
      ]
    }
  },
  "extensions": {}
}

I'm very much uncertain as to what the issue is here, I have looked elsewhere and other examples seem fine, is it something to do with the gatsby-plugin-image perhaps?

Any help would be great as this seems to be quite a niche issue.

Thanks


Solution

  • edges is an array, and arrays do not have a node property, so edges.node evaluates to undefined. You then attempt to access heroImage on undefined, which throws the error.

    Instead consider using edges.map, for example:

    edges.map(({ node }, index) => <Img key={index} {...node.heroImage} />)
    

    For what it's worth, you can change your query to simplify this song and dance a fair bit:

    export const query = graphql`
      {
        heroImages: allContentfulHeroImage {
          nodes {
            heroImage {
              fluid (maxWidth: 2000) {
                ...GatsbyContentfulFluid
              }
            }
          }
        }
      }
    `
    

    Then you'd be able to map over data.heroImages.nodes, and instead of destructuring node from each item, you can use it as-is or destructure the properties you need on it. E.g.:

    data.heroImages.nodes.map(({ heroImage }, index) =>
      <Img key={index} {...heroImage} />
    )