Search code examples
gatsbystrapi

Multi images, cannot get first image from array


I have a gatsby app which is connected to a Strapi backend.
On my homepage i want to display all projects and their first image from the gallery.

My query looks like this:

        allStrapiProject {
          edges {
            node {
              title
              gallery{
                localFile{
                  publicURL
                  childImageSharp {
                    gatsbyImageData(
                      placeholder: BLURRED
                      formats: [AUTO, WEBP, AVIF]
                      layout: FULL_WIDTH
                    )
                  }
                }
              }
            }
          }
        }

my index.js looks like this

    <Layout>
      <div id="projects" className="featured-grid">
        {data.allStrapiProject.edges.map(({node: project}) => {
          const image = getImage(project.gallery[0].localFile);
          return (
            <div>
              <p>{project.title}</p>
              <GatsbyImage image={image} />
            </div>
          )
        })}
      </div>
    </Layout>

and i get this error

Error in function eval in ./src/pages/index.js:18
Cannot read properties of null (reading '0')

seems like its not letting me get the first value from the array. also when i do console.log(project.gallery) i can see all the arrays, but when i try to console.log(project.gallery[0]) i get the same error.

Any ideas ?

Edit* console.log(project.gallery)

enter image description here


Solution

  • The resolution has been:

    {
      project.category.name === "Photo" && (
        <GatsbyImage
          image={getImage(project.gallery[0].localFile)}
          alt="asdasdasd"
          className=""
        />
      );
    }
    

    The problem was that some categories don't contain gallery node so the approach should only apply to Photo