Is there a way to utilize a field as a filter in one graphql query to retrieve a dynamic image from a distinct query?

I'm currently working with two GraphQL sources - one for fluid images and the other for characters stored in a MongoDB database. My main task involves mapping these characters onto a page, using their names as filters to retrieve the corresponding image (based on the "originalName" field). Here is what my query looks like:

query MyQuery {
  allMongodbMobileLegendsdevChamps {
    nodes {
      name
    }
  }
  allImageSharp(filter: {fluid: {originalName: {eq: "characterName.jpg"}}}) {
    nodes {
      fluid {
        ...allImageSharpFluid
      }
    }
  }
}

const Index = ({ data }) => {
  const {
    allMongodbMobileLegendsdevChamps: { nodes: champs },
    allImageSharp: { nodes: fluid },
  } = data
  return (
    <section className={grid}>
      {champs.map(champ => {
        return (
          <Link to={`/champ/${champ.name}`}>
            <Image fluid={fluid.fluid} />
            <h3>{champ.name}</h3>
          </Link>
        )
      })}
    </section>
  )
}

If I were not using GraphQL, I would simply set the src attribute of the image to `"champ.name"` like this:

<Image src = `/path/to/img/${champ.name}.jpg` />

How can I filter my image query with the champ.name? Would utilizing Apollo be beneficial for this scenario?

Answer №1

Gatsby is currently unable to accept variables in queries due to limitations outlined in this GitHub issue https://github.com/gatsbyjs/gatsby/issues/10482

If it were possible to pass variables, I would structure all characters as a page query to manipulate the name from props, and then use a static query with the name as a filter.

Answer №2

After finding a helpful solution online, I decided to tweak it to better suit my project's requirements: Using Variables in graphQL queries

In the main component, I iterate through all the champions and generate a child component for each one, passing along the champion's name.

Within the child component, there is a variable called "name" that links to the correct node containing the image I need to display. By matching the champion's name with the image's relativePath (which shares the same exact name), I utilize the find method to locate the right image. The renderImage function then takes the "name" variable and locates the fluid image within node.childImageSharp.fluid, successfully creating the image component with the appropriate fluid image source.

import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import { displayName } from "../../utils/championName"
import * as S from "../styled/ChampionGridCard"

const renderImage = file => {
  return <S.ChampionImage fluid={file.node.childImageSharp.fluid} />
}

const ChampionGridCard = props => {
  const data = useStaticQuery(graphql`
    {
      allFile(filter: { sourceInstanceName: { eq: "champImages" } }) {
        edges {
          node {
            extension
            relativePath
            childImageSharp {
              fluid {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  `)

  const name = data.allFile.edges.find(
    image => image.node.relativePath === `ssbu/${props.champName}.jpg`
  )

  return (
    <S.ChampionGridCard to={`/champ/${props.champName}`}>
      <S.ChampionImageWrapper>{renderImage(name)}</S.ChampionImageWrapper>
    </S.ChampionGridCard>
  )
}

export default ChampionGridCard

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with getting v-cloak to function properly when dealing with asynchronous requests

I wanted to explore using the v-cloak directive to showcase a loading spinner while certain data properties in vue js are being loaded asynchronously for me to integrate into a table component. After successfully applying and styling my v-cloak styles on ...

How can we efficiently trigger a function that sends an axios request by leveraging data from a v-for loop?

Currently, I am developing an e-commerce platform using Rails and VueJS. In order to display the orders of a specific user, I have created a component file. Within this component, I am utilizing a v-for loop to iterate over and showcase all the information ...

Analyze the length of time and provide a percentage of similarity

Is it possible to compare two durations and calculate the percentage of similarity? Suppose I have a reference duration, as well as a second duration that needs to be compared with the first one. There is an 8% tolerance level, meaning that the second du ...

Obtaining user roles from server without using JWT tokens

My main objective is to provide user roles from the backend. For instance, if a user wishes to access resources in my backend, they can log in using Google credentials. The Angular app retrieves the access token from the Google authorization server and s ...

What causes req.sessions to show an empty object instead of the expected value?

I've been grappling with a small issue while learning express.js. I am struggling to save sessions in the browser so that users don't have to log in every time they visit. I am using cookie-session for this purpose. When I send the login data fro ...

How can you call a JavaScript function from C# using SignalR?

I have been struggling to get SignalR working despite the many examples available. I am hoping that someone can provide a clear demonstration of how a WebPage with a threaded loop can call a JavaScript method on a page to change a text label or create a po ...

Angular's sanitization script incorrectly modifies the URL value provided in the script src attribute

How can I safely sanitize an external URL to dynamically load a script and remove scripts for a specific component only? Here is the approach I have used: private sanitizeUrl(): SafeResourceUrl { // Value declared in the environment file return ...

What is the best method for retrieving a specific element nested within another element, employing a for loop and storing it in an array using JavaScript?

In my project, I was tasked with retrieving all the select and input elements that are nested within td elements in a table. My approach involved first fetching all the tds and storing them in an array. Then, I used a for loop to iterate through each td an ...

jQuery is experiencing issues when attempting to add multiple rows to a table

I am currently working on building a function that takes an input and uses it to construct a grid. My main focus at the moment is getting the grid functionality up and running, but I've run into a strange issue. Despite searching for hours, all the so ...

Experiencing an unexpected abundance of console logs when implementing React Hooks

I am attempting to retrieve data from an API. The desired result is being obtained, but when I attempt to log it to the console, it logs 4 times. Within my app.js, I am utilizing the fetchData function: import React, {useEffect, useState} from 'rea ...

Generate a new span element within a div element programmatically using Vuex

I have integrated an existing web application developed using vue.js. Below is the code snippet: function () { var e = this, t = e.$createElement, n = e._self._c || t; return e.messag ...

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...

Variability in the values returned by the useState hook

Currently, I am working on developing my initial user signup form, and I have encountered a challenge that seems relatively simple to resolve but goes beyond my current expertise. The issue pertains to the helperText for an MUI select component which is no ...

For an unknown reason, I am facing difficulties in using the Storage feature from @angular/fire in ANGULAR 16

Recently I started exploring Angular/Fire and decided to test out some of its features by creating a basic app. Firestore and authentication were working smoothly, but when I attempted to include Storage, an error message popped up: ERROR FirebaseError: ...

JavaScript is reliant on the presence of the alert() function to properly function

I have a JavaScript function that performs well, except for when I remove or comment out the alert() line. This function is designed to calculate the sum of values in up to 30 fields if they are present and contain a value. Here is an example of the HTML ...

Button click not triggering JQuery datepicker functionality

Currently, I am facing an issue with the jQuery datepicker functionality. It seems to work fine when clicking on a button in Mozilla Firefox, but unfortunately, it does not function properly in Google Chrome or Internet Explorer. Can someone please provide ...

Is it achievable to create a seamless fade in/out effect using jQuery?

I am experiencing a problem with smooth fading of image backgrounds on my website. Interestingly, this issue only occurs in Safari and Opera. In Firefox, Chrome, and IE7/8, you can see "frames" of the fade transition, almost like taking pictures. I am cu ...

What is the best approach for sending a binary image post request to an API using nodejs?

I am receiving the image binary in this manner: axios.get("image-url.jpg") Now, I want to utilize the response to create a new POST request to another server const form = new FormData(); const url = "post-url-here.com"; form.appe ...

Learn how to manipulate data within a MongoDB database schema using Node.js and Mongoose: inserting, saving, and updating records

When inserting data into the MongoDB schema presented below, make sure that Employee name, Project name, and client name can be the same, but the employee ID must be unique. Duplicate entries are not allowed. var StatusSchema = new mongoose.Schema({ ...

Tips for choosing a specific cell in a table

I currently have a total of 14 cells that have been generated. Is there a way for me to individually select and manipulate a specific cell out of the 14? I am looking to make only one cell unique, while leaving the rest to be displayed as they are in the ...