skip to Main Content

I’m trying to query all images in a folder and display them in a card grid with tailwindCSS and gatsby-image. I’ve been able to query and display one image, but when I try to do it with a folder of images, I get the error “TypeError: Cannot read property ‘edges’ of undefined” even though the query works in the GraphQL explorer. I’ve read the docs, looked at other tutorials, and tried it so many different ways now and can’t figure out what’s wrong. Any help is greatly appreciated!

import React from "react";
import { graphql } from "gatsby";
import Img from "gatsby-image";
import Layout from "../components/layout";
import SEO from "../components/seo";

const ArtPage = props => (
    <Layout>
      <SEO
        keywords={[`art`, `paint`, `draw`]}
        title="Art"
      />
      <div class="flex flex-wrap mt-2 mx-1">
        {props.artImages.edges.map(img => (
          <div class="w-full md:w-1/2 lg:w-1/2 px-2 my-2">
            <div className="rounded overflow-hidden shadow-lg">
              <Img
                className="w-full"
                fluid={img.node.childImageSharp.fluid}
              />
            </div>
          </div>
        ))}
      </div> 
    </Layout>
)

export default ArtPage;

export const query = graphql`
  query artImages {
    allFile(filter: { relativePath: { regex: "/art/.*.png/" } } ) 
    {
      edges {
        node {
          relativePath
          name
          childImageSharp {
            fluid(maxWidth: 500) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    } 
  }
`;

2

Answers


  1. Chosen as BEST ANSWER

    I was using props.artImages instead of props.data.artImages ooooooops


  2. Debugging such an issue is always difficult. Since you stated that your query is correct in GraphiQL you probably made a mistake referencing the right attributes in the GraphQL tree. undefined is an indicator that you reference an object that does not exist.

    The secret weapon for debugging this issue is actually console.log(graphQlobject). Print the object in your browser and try acessing the attributes until you get it right.

    I will give you my HeaderSupplier component that I use in my project and reference the important bits with comments:

    import React from "react";
    import { graphql, useStaticQuery } from "gatsby";
    import GatsbyImage from "gatsby-image";
    import styled from "styled-components";
    import { pickRandomly } from "../util/utilityFunctions";
    
    /**
     * Returns one random image header.
     * Uses GatsbyImage and GraphQL to load images.
     * @see https://www.orangejellyfish.com/blog/a-comprehensive-guide-to-images-in-gatsby/
     */
    const HeaderSupplier = () => {
      const { allFile } = useStaticQuery(graphql`
        query {
          allFile(filter: {
            extension: {regex: "/(jpg)|(jpeg)|(png)/"}, 
            sourceInstanceName: {eq: "headers"}}) 
            // filter by sourceInstanceName, see the gatsby-config.js, 
            // this way you get exactly the files you need without complicated regex statements
          {
            edges {
              node {
                childImageSharp {
                  fluid(maxWidth: 150, quality: 100) {
                    originalName
                    ...GatsbyImageSharpFluid
                  }
                }
              }
            }
          }
        }`);
    
      // use console.log for debugging and correctly navigating the graphQL tree
      console.log(allFile);
    
      const header = pickRandomly(allFile.edges); 
      const { fluid } = header.node.childImageSharp;
      // make sure you reference the correct objects
      // if you get undefined you made a mistake navigating the GraphQL tree
    
      return (
          <GatsbyImage fluid={fluid} alt={fluid.originalName} />
      );
    };
    
    export default HeaderSupplier;
    

    The source instance in the gatsby-config.js:

    {
          resolve: "gatsby-source-filesystem",
          options: {
            path: `${__dirname}/src/components/library/headers`,
            name: "headers",
          },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search