question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Accessing the first, last, or middle item in my graphql query

See original GitHub issue

I have a graphql query grabbing every image inside a folder in my project. I am currently grabbing all images at once and it works.

const data = useStaticQuery(graphql `
        query {
            allFile(filter:{extension:{regex:"/(jpeg|jpg|gif|png)/"},  sourceInstanceName:{eq:"images"}}) {
                edges {
                    node {
                        childImageSharp {
                            fluid {
                                ...GatsbyImageSharpFluid
                            }
                        }
                    }
                }
            }
        }
    `)

{this.props.data.allFile.edges.map(({ node }) => (
    <Img fluid={node.childImageSharp.fluid}/>
))}

Is there a way to grab the first, last, or middle image out of that query? Something like this.props.data.allFile.edges.node[0].childImageSharp.Fluid? I know that isn’t correct syntax, but is there something that can achieve this?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
jonniebigodescommented, Dec 26, 2019

@brandontb12 i’ve picked up on your issue and i’m going to detail the steps taken to triage it.

  • Created a new Gatsby website using the default starter.
  • Created a new folder with the name random-images
  • Copied over some images that i usually use to triage issues that involve working with images.
  • Updated gatsby-config.js plugins to look up for the folder where my images are, turning it into:
module.exports = {
  ....
  plugins: [
   ....
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/random-images`,
      },
    },
  ...
  ],
}

  • Updated my src\pages\index.js to the following:

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

const IndexPage = () => {
  const imagesResult = useStaticQuery(graphql`
    {
      allFile(
        filter: {
          extension: { regex: "/(jpeg|jpg|gif|png)/" }
          sourceInstanceName: { eq: "images" }
        }
      ) {
        edges {
          node {
            childImageSharp {
              fluid {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  `)
  const { allFile } = imagesResult // destructure the allFile key from the query
  const { edges } = allFile // destructure the edges array from the above
  if (edges.length === 0) {
    return (
      <Layout>
        <SEO title="Home" />
        <h1>There are 0 images</h1>
      </Layout>
    )
  }
  const firstItem=edges[0].node // fetches the first item
  const midItem= edges[Math.ceil(edges.length/2)-1].node // fetches the mid item
  const lastItem= edges[edges.length-1].node // fetches the last item
  return (
    <Layout>
      <SEO title="Home" />
      <h1>Fetching images</h1>
      <p>First One</p>
      <Img fluid={firstItem.childImageSharp.fluid}/>
       <p>Mid item</p>
       <Img fluid={midItem.childImageSharp.fluid}/>
      <p>Last item</p>
      <Img fluid={lastItem.childImageSharp.fluid}/>
    </Layout>
  )
}

export default IndexPage

  • Running gatsby develop for a development build, or create a production build and serve it, emulating a production server with gatsby build && gatsby serve will display the items accordingly.

I’ve created a GitHub repo with the code, so that you can go about it at your own pace.

Feel free to provide feedback so that we can close this issue or continue to work on it until we find a suitable solution

0reactions
blainekastencommented, Dec 27, 2019

Thanks for jumping in @jonniebigodes ! ❤️

Read more comments on GitHub >

github_iconTop Results From Across the Web

3. Execute your first query - Apollo GraphQL Docs
Click this button to add the query to the middle "operations" panel: ... This is probably the easiest way to add fields to...
Read more >
Understanding Queries in GraphQL - DigitalOcean
In this tutorial, we'll take an in-depth look at queries in GraphQL so that you better understand how to retrieve data from a...
Read more >
GraphQL Tutorial: how to use fields, fragments, and more
GraphQL allows you to go beyond this simple operation with complex queries that navigate nested objects or modify fetched data using object ......
Read more >
GraphQL API - The Graph Docs
When querying a collection, the first parameter can be used to paginate from the beginning of the collection. It is worth noting that...
Read more >
Queries and Mutations - GraphQL
In that case, you can make a sub-selection of fields for that object. GraphQL queries can traverse related objects and their fields, letting...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found