3

I have a React Component that needs to query data. And I want to pass arguments/variables to the query. But I don't know how to do that.

For example. I have this blog item carousel that wants to query an x amount of items and an x amount of offset (skip first x number).

This is roughly what I have right now. But I don't know how to pass the variables inside the GraphQL query

import React from "react"
import {graphql, useStaticQuery} from "gatsby";
import BlockCarousel from "../blockCarousel/blockCarousel";


const BlockCarouselBlog = ({block,data}) => {

  let queryArgs = {
    limit: 10,
    skip: 0
  };
  
  block.blocks = GetBlogItems(queryArgs);

  return (
    <BlockCarousel block={block} data={data} />
  )
};
export default BlockCarouselBlog



const GetBlogItems = (args) => {

    let data = useStaticQuery(graphql`
      query {
        allSanityBlog(
          sort: { fields: [_createdAt], order: DESC }
          limit: 10 // this needs the variable
          skip: 0 // this needs the variable
        ) {
          ... rest of the data
        }


      }
    `)

    if (data.allSanityBlog.edges)
      return data.allSanityBlog.edges

    return null;
  }

The Question

How can I pass arguments into a Gatsby GraphQL query for a component?

Community
  • 1
  • 1
Tim
  • 861
  • 1
  • 12
  • 27
  • https://www.gatsbyjs.org/docs/data-fetching/ - contains link to example with apollo – xadm Mar 08 '20 at 13:59

1 Answers1

1

This problem is a Known limitation of Gatsby's useStaticQuery and not with GraphQL itself.

GraphQL clearly defines a way to use variables in a query. This require below 3 steps:

  1. Replace the static value in the query with $variableName
  2. Declare $variableName as one of the variables accepted by the query
  3. Pass variableName: value in the separate, transport-specific (usually JSON) variables dictionary

In your case I would suggest to get the arguments and use string interpolation to create the query before passing to useStaticQuery() function

Aditya Singh
  • 15,810
  • 15
  • 45
  • 67
  • Arg... that's, slightly put, a bummer... But that would make it extremely inflexible. I was looking at your string interpolation. Would you mean changing it to a line like `limit: ${args.limit}` ? Because this throws me an error: `BabelPluginRemoveGraphQLQueries: String interpolations are not allowed in graphql fragments` – Tim Mar 08 '20 at 11:52