GraphQL - Gatsby.js- React component. - How to query with variables/arguments?

Viewed 2066

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 Answers

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

Related