简体   繁体   中英

GatsbyJS - Adding Variables to graphQL

I'm building a dynamic gatsby app where users can log in and see a list of categories, and for each category a list of products. When a user clicks on a category, I want to dynamically render the relevant products through a graphQL query. How I want to do this is through grabbing the category slug from the URL and passing that to a graphQL query, but I keep getting errors when I pass a variable.

I've pasted my query below without a variable. Instead of "Serverless", I want a variable ${slug}.

export const query = graphql`
{ 
    fauna {
        slugMap (slug: "serverless"){
                data{
            name
            companies{
            data{
                name
                website
                description
            }
            }
        }

        }
  }
}
`

Gatsby-node.js

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions
  // Only update the `/app` page.
  if (page.path.match(/^\/map/)) {
    // page.matchPath is a special key that's used for matching pages
    // with corresponding routes only on the client.
    page.matchPath = "/map/*"
    // Update the page.
    createPage(page)
  }
}

Gatsby queries are used for querying internal state during development or build process - it's not active (not exists) after deploying.

For dynamic querying you need active/live data source - fe some graphql server. You can use either graphql client (fe apollo) or fetch (POST json graphql requests). This is explained in gatsby dosc - data-fetching

To do that, you need to change your graphql query to look something like this:

export const query = graphql`
{ 
    query FaunaBySlug($slug: String!) {
        fauna {
            slugMap (slug: {eq: $slug }){
                data {
                    name
                    companies {
                    data {
                        name
                        website
                        description
                    }
                }
            }
        }
    }
}

Then in your gatsby-node you need to pass the slug via context.

  createPage({
    path: 'page/',
    component: template,
    context: {
      slug: category.slug,
    }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM