habudu
habudu

Reputation: 303

Passing Variables into GraphQL Query in Gatsby

I want to limit the number of posts fetched on my index page. Currently, the number of pages is hard-coded into the GraphQL query.

query {
    allMarkdownRemark(limit: 5, sort: { fields: [frontmatter___date], order: DESC }) {
      totalCount
      edges {
        node {
          ...
        }
      }
    }
  }

I want to replace "5" with the value of a variable. String interpolation will not work with the graphql function, so I have to use another method.

Is there a way to achieve this and pass variables into a GraphQL query in GatsbyJS?

Upvotes: 1

Views: 2297

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29320

You can only pass variables to GraphQL query via context since string interpolation doesn't work in that way. In page query (rather than static queries) you can pass a variable using the context object as an argument of createPage API. So, you'll need to add this page creation to your gatsby-node.js and use something like:

const limit = 10;

page.forEach(({ node }, index) => {
  createPage({
    path: node.fields.slug,
    component: path.resolve(`./src/pages/index.js`), // your index path
    // values in the context object are passed in as variables to page queries
    context: {
      limit: limit,
    },
  })
})

Now, you have in your context object a limit value with all the required logic behind (now it's a simple number but you can add there some calculations). In your index.js:

query yourQuery($limit: String) {
    allMarkdownRemark(limit: $limit, sort: { fields: [frontmatter___date], order: DESC }) {
      totalCount
      edges {
        node {
          ...
        }
      }
    }
  }

Upvotes: 4

Related Questions