Reputation: 163
I'm building a blog with products, each product belongs to several categories. You can click a certain category, and it will take you to a page that only displays products that have that category.
Right now, i'm getting all products on every "category page", and use JS to filter the products, but i want to only load data that i need from the start.
Issue is that the variable that i'm suppost to filter by, is a variable that i compute from location.pathname; (I removed a lot of not relevant code from the snippet)
How can i find a syntax that allows me to add another filter to this query, that uses the "category" variable from this template component?
render() {
const { classes } = this.props
const posts = get(this, 'props.data.allContentfulBlog.edges')
const edges = this.props.data.allContentfulBlog.edges
const category = location.pathname
return (
<div className={classes.container}>
</div>
)
}
query categoryPostQuery {
allContentfulBlog(
filter: { node_locale: { eq: "en-US" } }
sort: { fields: [date], order: DESC }
) {
edges {
node {
id
categories
date(formatString: "DD MMMM, YYYY")
slug
}
}
}
}
I am supposed to enter the categories field, which is an array, and check if it includes the "category" variable.
Upvotes: 1
Views: 875
Reputation: 1516
This can be accomplished using Gatsby's query variables:
query categoryPostQuery($category: String) {
allContentfulBlog(
filter: { node_locale: { eq: "en-US" }, categories: { in: [$category] } }
sort: { fields: [date], order: DESC }
) {
edges {
node {
id
categories
date(formatString: "DD MMMM, YYYY")
slug
}
}
}
}
And the category
variable can be set using the context
option in gatsby-node.js
createPages:
createPage({
path,
component: categoryTemplate,
// If you have a layout component at src/layouts/blog-layout.js
layout: `blog-layout`,
context: {
category: 'games'
},
})
Upvotes: 2