Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables in graphQL queries

EDIT: now with working code below

The GraphiQL version

I have this query to fetch a gatsby-image:

query getImages($fileName: String) {
  landscape: file(relativePath: {eq: $fileName}) {
    childImageSharp {
      fluid(maxWidth: 1000) {
        base64
        tracedSVG
        aspectRatio
        src
        srcSet
        srcWebp
        srcSetWebp
        sizes
        originalImg
        originalName
      }
    }
  }
}

And then this query variable:

{
  "fileName": "titanic.jpg"
}

The above works fine in GraphiQL.

The Gatsby version

Now I want to use it in Gatsby, so I have the following code:

import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"

export default ({ data }) => (
  <div>
    <Img fluid={data.landscape.childImageSharp.fluid} />
  </div>
)

export const query = (
  graphql`
    query getImages($fileName: String) {
      landscape: file(relativePath: {eq: $fileName}) {
        childImageSharp {
          fluid(maxWidth: 1000) {
            base64
            tracedSVG
            aspectRatio
            src
            srcSet
            srcWebp
            srcSetWebp
            sizes
            originalImg
            originalName
          }
        }
      }
    }
  `,
  {fileName: "knight.jpg"}
)

The above doesn't work. data.landscape.childImageSharp === null

What am I doing wrong?

EDIT:

The working version

Thanks for the help! The following code works pretty well. This post was particularly helpful. This is not an ideal solution, but it works for me.

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

function renderImage(file) {
  return (
    <Img fluid={file.node.childImageSharp.fluid} />
  )
}

const MyImg = function (props) {

  return <StaticQuery
    query={graphql`
      query {
        images: allFile(filter: { sourceInstanceName: { eq: "images" } }) {
          edges {
            node {
              extension
              relativePath
              childImageSharp {
              fluid(maxWidth: 1000) {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
    `}
    render={(data) => {
      const image = data.images.edges.find(
        image => image.node.relativePath === "knight.jpg"
      )
      return(renderImage(image))
    }}
  />
}

export default MyImg;
like image 777
crowhill Avatar asked Dec 16 '18 16:12

crowhill


People also ask

Is it possible to use variables in a GraphQL query?

There are a variety of different variable data types available on Contentful's GraphQL API. As well as the standard data types such as String, Int and DateTime, you can also pass variables to a query that are entry-specific and API-specific.

How do you pass parameters in GraphQL query?

When you're passing arguments in code, it's generally better to avoid constructing the whole query string yourself. Instead, you can use $ syntax to define variables in your query, and pass the variables as a separate map. . then(data => console.

How do you use variables in GraphiQL?

The GraphiQL client allows you to create variables for use in your queries. To add a query variable, click the Query Variables pane and enter a JSON object that defines your variable. To use a variable in your query, prepend the $ character to your variable name and use it to replace the desired value.

How do you pass two arguments in GraphQL query?

Multiple arguments can be used together in the same query. For example, you can use the where argument to filter the results and then use the order_by argument to sort them.


2 Answers

The two answers (from Bens and Nimish) are wrong in this context, they're not specific to Gatsby.

If you want to use variables in the GraphQL queries, you have to pass them via context in the createPage function in gatsby-node.js as explained here: https://www.gatsbyjs.org/docs/programmatically-create-pages-from-data/

You currently can't use variables outside of that, e.g. have a look at this discussion: https://spectrum.chat/?t=abee4d1d-6bc4-4202-afb2-38326d91bd05

like image 104
LekoArts Avatar answered Oct 19 '22 23:10

LekoArts


So to pass variables you have to use the following syntax

graphql(`<your_query_with_variable>`, { indexPage: <value_of_variable> })

So the query will come something like this

    export const query = grapqhl(
     `query getImages($fileName: String) {
      landscape: file(relativePath: {eq: $fileName}) {
        childImageSharp {
          fluid(maxWidth: 1000) {
            base64
            tracedSVG
            aspectRatio
            src
            srcSet
            srcWebp
            srcSetWebp
            sizes
            originalImg
            originalName
           }
         }
       }
     }
    `,
    {fileName: "knight.jpg"}
   )
like image 33
Nimish Gupta Avatar answered Oct 19 '22 23:10

Nimish Gupta