llamerr
llamerr

Reputation: 3186

Gatsby - how to pass variables to pageQuery

I have same problem as in How do you pass variables to pageQuery, but for some reason solution not working for me

console.log inside template shows that data passed properly to component and pageContext is {cat: "Cat Name", limit: 10}, but query result returns items with category different from applied filter. Same query works fine and returns filtered list inside GraphiQL explorer.

my template component:

const Page: FC<unknown> = ({pageContext}): React.ReactElement => {
  const data = useStaticQuery(query)
  console.log(data, query, pageContext)

...

const query = graphql`
  query GetItems($cat: String, $limit: Int) {
    items: allItems(limit: $limit, filter: { category: { eq: $cat } }) {

my creatPage part:

console.log(cat)
createPage({
      path: `cat/${cat.slug}`,
      component: template,
      context: {
        cat: cat.title,
        limit: 10
      },
    })

So the question is - what am I doing wrong, and what can I do to debug it?

EDIT: so I did not read docs carefully enough, and useStaticQuery I copy-pasted from other pages can't accept variables. I tried to remove it, but did not get data prop in my component. I will update question bit later with additional information on what I changed.

Upvotes: 0

Views: 392

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29315

Assuming:

{cat: "Cat Name", limit: 10}

I don't know if it's a typo, but title is not a property of cat. If so, fix it, otherwise, cat: cat.title, will become undefined.

In addition, you can create a sample query to be used in the localhost:8000/___graphql by adding manually the context values:

  query GetItems {
    items: allItems(limit: 10, filter: { category: { eq: "Cat Name"} }) {

     ...
    }

Then, you will be able to test your expected results accordingly.

Upvotes: 1

Related Questions