Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass variables to pageQuery

Tags:

gatsby

I have this page in Gatsby:

import React from 'react'
import Link from 'gatsby-link'

import IntroPartial from '../partials/themes/intro'

export default class ThemeTemplate extends React.Component {
  render(){
    const theme = this.props.pathContext.theme
    console.dir(this.data)
    return (
      <div>
        <h1>{theme.name}</h1>
        <IntroPartial theme={theme} />
      </div>
    )
  }
}

export const pageQuery = graphql`
query ThemeQuery($theme: String){
  allMarkdownRemark(
    filter: { frontmatter: { themes: { in: [$theme] } } }
  ){
    edges{
      node{
        frontmatter{
          title
          themes
        }
        html
      }
    }
  }
}
`

This query works fine in the GraphQL tester assuming I supply an option to $theme. How do I provide the value for $theme? I'd like to set it to this.props.pathContext.theme.slug.

The docs seem to imply that some variables should just work, but I'm not sure how to add my own.

like image 633
Arcath Avatar asked Sep 22 '17 12:09

Arcath


People also ask

What is a static query?

A static query is like taking a snapshot of your database at the time the query is created. Only the records selected when the query is first created will be included when the query is used in the program. Use static queries when doing global changes.

How do I open GraphiQL?

To access the GraphiQL interface, type the URL or IP address for SL1 in a browser, add /gql to the end of the URL or IP address, and press Enter. GraphiQL is not maintained by ScienceLogic. You can access its documentation at https://github.com/graphql/graphiql.


1 Answers

The variables passed into graphql are coming from createPage. It's normally called in your gatsby-node file. You'll often see path used, as $path, in examples as it is required.

In order to include your own, additional variables to pass into the graphql call, you'll need to add them to context. Modifying the example from the docs a bit:

createPage({
  path: `/my-sweet-new-page/`,
  component: path.resolve(`./src/templates/my-sweet-new-page.js`),
  // The context is passed as props to the component as well
  // as into the component's GraphQL query.
  context: {
   theme: `name of your theme`,
 },
})

You can then use $theme in the query as you have in your example. Setting $theme in the above code would be done in the createPages portion (see the example), as you'll then have access to all of the data.

like image 84
Mark Michon Avatar answered Oct 22 '22 10:10

Mark Michon