Render Contentful Reference (many) Array on Gatsby

Viewed 491

I am pretty new to using Contentful and their Reference (many) field type. I have one reference type that pulls in many product names. in GraphQL I can see all my product name displaying, but when I try and render it on Gatsby I am not seeing anything display (productName:array). Here is my GraphQL

{
  allContentfulAppetizerMenuSection {
      nodes {
        menuItemReferences {
          productName
        }
      }
  }
}

and here is my code...

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

const Products = () => (

  <StaticQuery
  query={graphql`
    query MyQuery {
        allContentfulAppetizerMenuSection {
            nodes {
              menuItemReferences {
                productName
              }
            }
        }
    }
  `}

  render={data => (
    <div>
        {data.allContentfulAppetizerMenuSection.nodes.map(({ menuItemReferences }, i) => (
        <div key={i}>
            {menuItemReferences.productName}
        </div>
      ))}
    </div>
    )}
  />
)
  
export default Products;

Any help will be much appreciated.

1 Answers

Try:

const Products = () => {
  const data = useStaticQuery(graphql`
      query {
          allContentfulAppetizerMenuSection {
              nodes {
                  menuItemReferences {
                      productName
                  }
              }
          }
      }
  `);

  return <div>
    {data.allContentfulAppetizerMenuSection.nodes.map(({ menuItemReferences }, i) => {
      return <div key={i}>
        {menuItemReferences.productName}
      </div>;
    })}
  </div>;
};

export default Products;

Note the usage of useStaticQuery hook and the return statement in your loop.

The refactor upon useStaticQuery results in a cleaner and reusable code but the idea it's exactly the same, if you are more familiar with the old StaticQuery, you can keep it.

If the error persists, try to debug inside the loop.

Related