Search code examples
reactjsgraphqlgatsby

How to use variables in components with Gatsby Graphql


I am using gatsby with Wordpress, I have a component that should load some posts according to a variable category, the idea is to be able to use that component in several places, but I have not been able to find the way to do it.

This is the component

import * as React from "react"
import { useStaticQuery, graphql, Link } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
import './styles/bloque1.css';

const Bloque1 = ({Titulo, PostID}) => {
  const data = useStaticQuery(graphql`
   query {
     allWpPost(
       limit: 3
       filter: {categories: {nodes: {elemMatch: {databaseId: {eq: ${PostID} }}}}}
     ) {
       nodes {
         title
         slug
         date
         featuredImage {
          node {
            sourceUrl
            localFile {
              childImageSharp {
                gatsbyImageData
              }
            }
          }
        }
       }
     }
   }
   `)

  return (
    <div className="ct-blq-1">
      <h2>{Titulo}</h2>
      {data.allWpPost.nodes.map(element => 
      <div className="container-img">
        <GatsbyImage image={getImage(element.featuredImage.node.localFile)} alt=""  className="img"/>
        <div className="blq-1-item">
          <Link to="https://www.valoraanalitik.com/2022/04/12/j-p-morgan-rebajo-recomendacion-adr-bancolombia/"
            rel="bookmark" title={element.title}>
            <div className="nota-titulo">
              <h3>{element.title}</h3>
            </div>
            <div className="nota-tiempo">
              <time>{element.date}</time>
            </div>
          </Link>
        </div>
      </div>)}
    </div>
  )
}

export default Bloque1

I am looking for a way to use the PostID in {databaseId: {eq: ${PostID} }}

const Page = () => (
    <section id="page">
        <main>

            <Bloque1 Titulo="Noticias Destacadas" PostID="2"/>

            <Bloque2 />
        </main>
    </section>
)


Solution

  • You can't use dynamic variables in a static query (hence the name). It's a known limitation:

    • useStaticQuery does not accept variables (hence the name “static”), but can be used in any component, including pages
    • Because of how queries currently work in Gatsby, we support only a single instance of useStaticQuery in a file

    That said, depending on what you are trying to achieve, you can use a page query or using a template. To use variables in page queries, you need to provide them using context, not via props as you were trying to when you generate the page. If you are not generating page using gatsby-node.js, you can always fetch all posts (allWpPost) and filter them using JavaScript with the provided postID.

    There are a lot of implementation details missing to provide a full snippet but you can adapt your WordPress structure to this tutorial: https://www.gatsbyjs.com/docs/creating-and-modifying-pages/