Search code examples
reactjscontentfulgatsby

Show Contentful product using GatsbyJS


I am pulling in data from Contentful api into gatsby and all seems to be tracing out fine. However when I implement the component that pulls in the contentful data on to my index.js file I keep getting an undefined error.

WebpackError: Cannot read property 'allContentfulProduct' of undefined

Product.js:

import React from "react"

const Product = ({data}) => {
  const assets = data.allContentfulProduct.edges[0].node
  const { productName } = assets;

 return (
    <div>
      {productName}
    </div>
  )
};

export default Product;



export const pageQuery = graphql`
  query ImageAPIExamples {
    allContentfulProduct {
      edges {
        node {
          id
          productName
        }
      }
    }
  }
`

Index.JS

import React from 'react';
import Products from '../components/products/image';

const IndexPage = props =>
  (<main>
    Hello
  </main>);

export default IndexPage;

Solution

  • So it looks like I was able to solve this by passing props and querying the data on the index.js page.

    Solution:

    Index.js:

    import React from 'react';
    import Products from '../components/products/image';
    
    
    const IndexPage = props =>
      (<main>
        <Products data={props.data.allContentfulProduct.edges[0].node} />
      </main>);
    
    export default IndexPage;
    
    export const pageQuery = graphql`
      query IndexQuery {
        allContentfulProduct {
          edges {
            node {
              id
              productName
              image {
                file{
                  url
                }
              }
            }
          }
        }
      }
    `;