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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.