Reputation: 497
I have created page query for my individual product page.
It does goes to an individual product and I want to add a filter like if multiple product has similar SKU I need to show them. Query works fine in Grphiql interface but in code it only show one node.
Grahiql Query
query ($id: String, $sku: String) {
productsCsv(id: {eq: $id}) {
id
name
productCategory
sizes
sku
stock
instock
description
colors
templateKey
price
discount
fields {
slug
}
}
allProductsCsv(filter: {sku: {regex: $sku}, instock: {eq: "TRUE"}}) {
edges {
node {
id
instock
stock
sku
colors
sizes
}
}
}
}
In query Variables section, I am passing variable like this
{
"sku": "/DW20DK18/"
}
allProductCsv only resulted in one node in gatsby though it returns multiple nodes in graphiql
Gatsby-node.js
const { createFilePath } = require("gatsby-source-filesystem")
const path = require(`path`)
const onCreateNode = ({node,actions,getNode}) => {
const {createNodeField} = actions
if(node.internal.type === `MarkdownRemark`) {
const value = createFilePath({node, getNode})
createNodeField({
name:`slug`,
node,
value
})
}
if(node.internal.type === `ProductsCsv`) {
const value = node.name
const processedSlug = value.replace(/\s+/g, '-').toLowerCase();
createNodeField({
name:`slug`,
node,
value: processedSlug
})
}
}
const createPages = async ({actions,graphql}) => {
const {createPage} = actions
const result = await graphql(`
{
allMarkdownRemark {
edges {
node {
frontmatter {
productColors
age
}
}
}
}
allProductsCsv {
edges {
node {
id
sku
fields{
slug
}
templateKey
productCategory
}
}
}
}
`)
if(result.errors){
console.error(result.errors)
}
result.data.allProductsCsv.edges.forEach(({ node }) => {
console.log(node.productCategory)
createPage({
path: `${String(node.productCategory)}/${node.fields.slug}`,
component: path.resolve(
`src/templates/${String(node.templateKey)}.js`
),
context: {
id: node.id,
sku: `/${node.sku}/`.toString(). //Passing SKU from Here
}
})
})
}
module.exports = {
/*
1. function for how to create page
2. On create node
*/
onCreateNode,
createPages
};
I am passing SKU along side of ID in Context in gatsby-node.js
Upvotes: 3
Views: 2041
Reputation: 29315
Your workaround should work except for the fact that you are using a template literal to hold a dynamic regular expression. For this approach I would try to do something like:
context: {
id: node.id,
sku: new RegExp(String.raw `${node.sku}`, 'i'), //add other flags if needed
}
Alternatively try:
new RegExp(node.sku, 'i').toString()
The RegExp
constructor should do the trick for this use-case with a little trick to force a raw string (since the comparison within GraphQL needs to be represented by a string value).
Upvotes: 1