2

First time posting here, but I've been struggling with this for a few days now.

Basically I have a graphQL query that pulls in product data from contentful and then display it on a GatsbyJS page. The query correctly displays for the title, price, and description of the product but it wont load in the image. Unfortunately I keep receiving errors such as:

"TypeError: Cannot read property '0' of undefined"

or

Cannot read property 'src' of undefined. (When changing the query to look at the src of an image. When I do this method, the url does have a value according to GraphiQL)

here's the code for the page I am currently working on:

import React from 'react'
import { graphql } from 'gatsby'
import Img from 'gatsby-image'

import Layout from '../components/Layout'
import './shop.scss'

const Shop = ({ data }) => {

    return (
        <Layout>
            <section>
              {data.allContentfulProducts.edges.map( ({ node }) => (
                <article key={node.id}>
                  <Img
                    fluid={node.images.fluid}
                  />
                  <p>{node.productName}</p>
                </article>
              ))}
            </section>
        </Layout>
    )
}

export const productQuery = graphql`
  query {
    allContentfulProducts {
      edges {
        node {
          id
          productName
          images {
            fluid {
              ...GatsbyContentfulFluid
            }
          }
        }
      }
    }
  }
`

export default Shop
Jeremy
  • 21
  • 2
  • Do you add a single image to the product in contentful, or do you add multiple _images_? If it is multiple, that would suggest that _images_ is an array, and you need to map over `node.images` before accessing each of their `fluid` properties. – ksav Feb 05 '20 at 06:27
  • provide sample data - `images` parts - images defined for all products? – xadm Feb 05 '20 at 09:45
  • 1
    thank you so much. Oh I feel dumb. It didn't occur to me that my image field in the content model was an array for some reason. I fixed it by adding node.images[0].fluid. – Jeremy Feb 06 '20 at 02:55

1 Answers1

0

I think there is a problem with you graphQL Query. Try this one:

export const productQuery = graphql`
  query {
    allContentfulProducts {
      edges {
        node {
          id
          productName
          image {
            fluid {
              src
              ...GatsbyContentfulFluid
            }
          }
        }
      }
    }
  }
`

If this query is not helping please show us the structure of your contentful assets.

Kingalione
  • 4,237
  • 6
  • 49
  • 84