Reputation: 471
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)
}
}
Upvotes: 0
Views: 1040
Reputation: 8418
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 - f.e. some graphql server. You can use either graphql client (f.e. apollo) or fetch
(POST json
graphql requests). This is explained in gatsby dosc - data-fetching
Upvotes: 2
Reputation:
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,
}
});
Upvotes: 1