Variable "$productSlug" is never used in operation "SingleProduct". Graphql error. Variables are not working in my Gatsby graphql queries - graphql

I am getting this error: Variable "$productSlug" is never used in operation "SingleProduct".
I also use gatsby-source-wordpress to query fields from wordpress to gatsby. I also uninstalled Gatsby and re-installed it to see if it works in different versions, but it didn't.
I searched all over the internet and stack overflow for an answer, I really believe it must be a bug with Gatsby or gatsby-source-wordpress,
this is the code:
const path = require("path");
const { createFilePath } = require(`gatsby-source-filesystem`);
exports.onCreatePage = ({ page, actions }) => {
const { createPage } = actions;
if (page.path.match(/products/)) {
page.context.layout = "ArchiveProduct";
createPage(page);
}
if (page.path.match(/products\/([^\/]+$)/)) {
page.context.layout = "SingleProduct";
createPage(page);
}
};
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions;
if (node.internal.type === `allWpProduct`) {
const slug = createFilePath({ node, getNode, basePath: `pages` });
createNodeField({
node,
name: `slug`,
value: slug,
});
}
};
exports.createPages = async function ({ graphql, actions }) {
const { data } = await graphql(`
query SingleProduct {
allWpProduct {
nodes {
uri
slug
id
}
}
}
`);
data.allWpProduct.nodes.forEach((node) => {
// const slug = node.slug;
actions.createPage({
path: "/products/" + node.slug,
component: path.resolve("./src/templates/SingleProduct.js"),
context: {
productSlug: node.slug,
productId: node.id,
layout: "SingleProduct",
},
});
});
};
And this is the query:
export const query = graphql`
query SingleProduct($productSlug: String!) {
wpProduct(slug: { eq: "$productSlug" }) {
title
slug
link
id
date(formatString: "MMMM DD, YYYY")
product {
description
price
slug
photo {
localFile {
childImageSharp {
gatsbyImageData
}
}
}
}
}
}
`;

Try the following:
export const query = graphql`
query SingleProduct($productSlug: String!) {
wpProduct(filter: {slug: { eq: "$productSlug" }}) {
title
slug
link
id
date(formatString: "MMMM DD, YYYY")
product {
description
price
slug
photo {
localFile {
childImageSharp {
gatsbyImageData
}
}
}
}
}
}
`;
Your issue appears because $productSlug is lifted properly via context but never used in any sort of filtering action inside the query.
I'd recommend you check it before in the GraphiQL playground hardcoding the $productSlug to check the output.

Related

How to update nested structures in apollo cache using cache.modify

fragment commentFragment on Comment {
id
text
galleryId
commentUser {
id
firstName
lastName
}
}
fragment galleryFragment on Gallery {
id
path
label
comments {
...commentFragment
}
}
We first retrieve the getGalleries using the following gql :
query getGalleries($filters: galleryFilterInput) {
getGalleries(filters: $filters) {
galleries {
...galleryFragment
}
cursor
hasMore
}
}
Now when the user enters a comment on a single gallery item we run the following mutation :
mutation addCommentMutation($input: addCommentInput!) {
addComment(input: $input) {
...commentFragment
}
}
Now, we were previously using refetchQueries to update the Galleries but we have now decided to use cache.modify however we are having problem with updating the galleries
update: (cache, data: any) => {
cache.modify({
fields: {
getGalleries(existing, { readField }) {
const comment = data.data.addComment;
const newEventRef = cache.writeFragment({
fragment: commentFragment,
data: comment,
fragmentName: "commentFragment",
});
const index = existing.galleries.findIndex(
aGallery => aGallery.id === comment.galleryId
);
if (index !== -1) {
const existingCommentRef = readField("comments", existing.galleries[index])
as readonly Reference;
const newCommentsRefs = [...existingCommentRef, newRef];
cache.writeFragment({
id: "Gallery:" + readField("id", existing.galleries[index]),
fragment: gql`
fragment comments on Gallery {
comments {
...commentFragment
}
}
`,
data: newCommentsRefs,
});
}
return existing;
},
},
});
},
I am unsure how I update the newCommentsRefs in that Gallery
update(cache, data) {
const comment = data.data.addComment;
cache.writeFragment({
fragment: commentFragment,
data: comment,
fragmentName: "commentFragment",
});
const gallery: Gallery = cache.readFragment({
id: `Gallery:${comment.galleryId}`,
fragment: galleryFragment,
fragmentName: 'galleryFragment'
});
if (gallery) {
const newComments = [...gallery.comments, comment]
cache.writeFragment({
id: `Gallery:${comment.galleryId}`,
fragment: galleryFragment,
fragmentName: 'galleryFragment',
data: { ...gallery, comments: newComments }
});
}
}

WpGraphQL query returns null

I'm having this GraphQL query from headless Wordpress in Nexjs via WpGraphQl plugin:
export const GET_POSTS_BY_CATEGORY_SLUG = gql`
query GET_POSTS_BY_CATEGORY_SLUG( $slug: String, $uri: String, $perPage: Int, $offset: Int ) {
${HeaderFooter}
page: pageBy(uri: $uri) {
id
title
content
slug
uri
seo {
...SeoFragment
}
}
categories(where: {slug: $slug}) {
edges {
node {
slug
posts: posts(where: { offsetPagination: { size: $perPage, offset: $offset }}) {
edges {
node {
id
title
excerpt
slug
featuredImage {
node {
...ImageFragment
}
}
}
}
pageInfo {
offsetPagination {
total
}
}
}
}
}
}
}
${MenuFragment}
${ImageFragment}
${SeoFragment}
`;
And this is my getStaticProps function:
export async function getStaticProps(context) {
const { data: category_IDD } = await client.query({
query: GET_POSTS_BY_CATEGORY_SLUG,
});
const defaultProps = {
props: {
cat_test: JSON.parse(JSON.stringify([category_IDD])),
},
revalidate: 1,
};
return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}
If i pass it like this in props:
const defaultProps = {
props: {
cat_test: category_IDD,
},
i get an error saying:
SerializableError: Error serializing `.cat_test` returned from `getStaticProps` in "/category/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
But when i JSON.parse as the code above, i get null
Whats wrong with this query?
Just noticed that the $slug is an array of strings, so here should be:
query GET_POSTS_BY_CATEGORY_SLUG( $slug: [String], $uri: String, $perPage: Int, $offset: Int )
instead of $slug: String
You're not actually passing the $slug variable to the query.
For instance if your page route is /category/[slug].js your getStaticProps should look something like this.
export async function getStaticProps(context) {
const { slug } = context.params;
const { data: category_IDD } = await client.query({
query: GET_POSTS_BY_CATEGORY_SLUG,
variables: { slug },
});
const defaultProps = {
props: {
cat_test: JSON.parse(JSON.stringify([category_IDD])),
},
revalidate: 1,
};
return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}

In Gatsby how do I pass a relative path file to a template that is also pulling a query?

In Gatsby I've coded a single post template:
singlePost.js:
import React from 'react'
import { graphql } from 'gatsby'
import { MDXRenderer } from 'gatsby-plugin-mdx'
import { H1 } from '../elements'
import { Container, Post, FeatureImage } from '../components'
const singlePost = ({ data }) => {
const featureImage = data.mdx.frontmatter.featureImg.childImageSharp.fixed
return (
<Container>
<FeatureImage fixed={featureImage} />
<Post>
<H1 margin=" 0 0 2rem 0">{data.mdx.frontmatter.title}</H1>
<MDXRenderer>{data.mdx.body}</MDXRenderer>
</Post>
</Container>
)
}
export const pageQuery = graphql`
query SinglePostQuery($id: String!) {
mdx(id: { eq: $id }) {
body
frontmatter {
date
excerpt
featureImg {
childImageSharp {
fixed(width: 1920) {
...GatsbyImageSharpFixed
}
}
}
title
slug
}
}
}
`
export default singlePost
In my gatsby-node.js I get the data from the slug:
data.allMdx.edges.map(edge => {
const slug = edge.node.frontmatter.slug
const id = edge.node.id
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/singlePost.js`),
context: { id },
})
})
In the frontmatter of the markdown file there is a feature image:
---
title: Bacon Ipsum
slug: bacon
date: 2021-02-09
featureImg: nature.jpg
excerpt: Bacon ipsum dolor amet pastrami prosciutto meatball fatback, andouille drumstick shank burgdoggen brisket cow turkey.
---
if the post markdown file doesn't have an image I get an error of:
Cannot read property 'childImageSharp' of null
I can access the default image I've set with:
const defaultImage = useStaticQuery(graphql`
query {
default: file(relativePath: { eq: "default.jpg" }) {
publicURL
}
}
`)
but when I try to query for the content and the default with:
const defaultImage = useStaticQuery(graphql`
query SinglePostQuery($id: String!) {
mdx(id: { eq: $id }) {
body
frontmatter {
date
excerpt
featureImg {
childImageSharp {
fixed(width: 1920) {
...GatsbyImageSharpFixed
}
}
}
title
slug
}
}
default: file(relativePath: { eq: "default.jpg" }) {
publicURL
}
}
`)
I get an error of:
If you're not using a page query but a useStaticQuery / StaticQuery
you see this error because they currently don't support variables.
In Gatsby how can I query the slug but also have pass the default image to the Feature Image component?
As the error log points, useStaticQuery (because it's a type of static query) doesn't accept variables, hence the name.
In Gatsby how can I query the slug but also have pass the default
image to the Feature Image component?
You can use the same context where you attach the id to pass the image while using page queries.
data.allMdx.edges.map(edge => {
const slug = edge.node.frontmatter.slug
const id = edge.node.id
const imagePath = edge.node.featureImg || 'default.jpg'
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/singlePost.js`),
context: {
id
imagePath
},
})
})
Note: You may need to query the image in your gatsby-node.js. Change the imagePath to another identifier that matches better your data structure if needed.
Then, in your template:
import React from 'react'
import { graphql } from 'gatsby'
import { MDXRenderer } from 'gatsby-plugin-mdx'
import { H1 } from '../elements'
import { Container, Post, FeatureImage } from '../components'
const singlePost = ({ data }) => {
const featureImage = data.mdx.frontmatter.featureImg.childImageSharp.fixed
return (
<Container>
<FeatureImage fixed={featureImage} />
<Post>
<H1 margin=" 0 0 2rem 0">{data.mdx.frontmatter.title}</H1>
<MDXRenderer>{data.mdx.body}</MDXRenderer>
</Post>
</Container>
)
}
export const pageQuery = graphql`
query SinglePostQuery($id: String!, $imagePath: String) {
mdx(id: { eq: $id }) {
body
frontmatter {
date
excerpt
featureImg {
childImageSharp {
fixed(width: 1920) {
...GatsbyImageSharpFixed
}
}
}
title
slug
}
}
default: file(relativePath: { eq: $imagePath }) {
publicURL
}
}
`
export default singlePost
Note: add the $imagePath as a nullable value (by removing the exclamation mark, !), since, as you said, not all the posts will have it.
Try removing the featureImg block if it stills breaking the query. Because of:
const imagePath = edge.node.featureImg || 'default.jpg'
Your imagePath variable will always contain the needed data,or your featureImg, or your default one. The key is to make separate queries.

Gatsby Contentful embedded image

As I see there is no json option anymore when querying the contentfulBlogPost only raw. I was able to make some changes to get everything from the body, except the image from that post.
If I made a test in GraphQL Playground I can get the image id and url but that's it.
query {
allContentfulAsset {
edges {
node {
id
file {
url
}
}
}
}
}
I tried to find an example how to get embedded images but no luck....
import React from 'react'
import { graphql } from 'gatsby'
import { documentToReactComponents } from '#contentful/rich-text-react-renderer'
import Layout from '../components/layout'
export const query = graphql`
query($slug: String!) {
contentfulBlogPost(slug: {eq: $slug}) {
title
publishedDate(formatString: "MMMM Do, YYYY")
body {
raw
}
}
allContentfulAsset {
edges {
node {
id
file {
url
}
}
}
}
}
`
const Blog = (props) => {
const options = {
renderNode: {
"embedded-asset-block": (node) => {
const alt = node.data.title
const url = node.file.url
return <img alt={alt} src={url}/>
}
}
}
return (
<Layout>
<h1>{props.data.contentfulBlogPost.title}</h1>
<p>{props.data.contentfulBlogPost.publishedDate}</p>
{documentToReactComponents(JSON.parse(props.data.contentfulBlogPost.body.raw, options))}
</Layout>
)
}
export default Blog
Plugins:
...
'gatsby-plugin-sharp',
{
resolve: 'gatsby-transformer-remark',
options: {
plugins: [
'gatsby-remark-relative-images',
{
resolve: 'gatsby-remark-images-contentful',
options: {
maxWidth: 750,
linkImagesToOriginal: false
}
}
]
}
}
],
}
Hi I saw this solution in a Youtube comment. First thing you have to do is change your Graphql query to something like this:
query ($slug: String!) {
contentfulBlogPost(slug: {eq: $slug}) {
id
title
publishedDate(formatString: "MMMM Do, YYYY")
body {
raw
references {
... on ContentfulAsset {
contentful_id
title
file {
url
}
}
}
}
}
}
Then change your options constant to:
const options = {
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: node => {
console.log(node);
const imageID = node.data.target.sys.id;
const {
file: {url},
title
} = props.data.contentfulBlogPost.body.references.find(({contentful_id: id}) => id === imageID);
return <img src={url} alt={title} />
}
}
}
Use something like:
import { BLOCKS, MARKS } from "#contentful/rich-text-types"
import { renderRichText } from "gatsby-source-contentful/rich-text"
​
const Bold = ({ children }) => <span className="bold">{children}</span>
const Text = ({ children }) => <p className="align-center">{children}</p>
​
const options = {
renderMark: {
[MARKS.BOLD]: text => <Bold>{text}</Bold>,
},
renderNode: {
[BLOCKS.PARAGRAPH]: (node, children) => <Text>{children}</Text>,
[BLOCKS.EMBEDDED_ASSET]: node => {
return (
<>
<h2>Embedded Asset</h2>
<pre>
<code>{JSON.stringify(node, null, 2)}</code>
</pre>
</>
)
},
},
}
​
renderRichText(node.bodyRichText, options)
Source: https://www.contentful.com/developers/docs/tutorials/general/rich-text-and-gatsby/
The return statement in BLOCKS.EMBEDDED_ASSET entry will contain your data, adapt to your needs. If you go inside the dependency, you'll see all the exposed methods, so you will have also a BLOCKS.EMBEDDED_ENTRY entry for your embedded entries. Apply it like:
[BLOCKS.EMBEDDED_ENTRY]: node => {
// your logic to manipulate the entry here
return (
<>
<div>whatever</div>
</>
)
},
For anyone that is still struggling to find the "references" field in graphql, remember that you HAVE TO first create an entry in contentful by adding at least one image. Otherwise, the references field will not show up in graphql, hence you can not query it.

How to add variables to graphQL query?

I am using Gatsby.
I need to increase the limit of 3 to each onCLick.
I've tried to follow this post, but with no success, so I removed the edits, and here is the original code...
This will help me to load more posts.
export const LatestNews = ({data}) => {
console.log(data);
return (
<section id="news_posts_section">
<p>some data</p>
</section>
);
};
export const latestNewsQuery = graphql`
query myquery{
allMarkdownRemark(
filter: { frontmatter: { layout: { eq: "news" } } }
sort: { fields: frontmatter___date, order: DESC }
limit: 2
) {
nodes {
frontmatter {
layout
title
path
date
featuredImage
thumbnail
}
excerpt(pruneLength: 325)
}
}
}
`;
Here is my gatsby-node:
exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions;
const blogPostTemplate = path.resolve('src/templates/blog-post/BlogPost.js');
const newsTemplate = path.resolve('src/templates/news-single/NewsSingle.js');
const latestNewsPage = path.resolve(
'src/components/pages-implementation/news/sections/LatestNews.js',
);
const blog = graphql(`
{
blog: allMarkdownRemark(
filter: { frontmatter: { layout: { eq: "blog" } } }
) {
edges {
node {
frontmatter {
path
}
}
}
}
}
`).then((result) => {
if (result.errors) {
result.errors.forEach((e) => console.error(e.toString()));
return Promise.reject(result.errors);
}
const posts = result.data.blog.edges;
posts.forEach((edge) => {
const { path } = edge.node.frontmatter;
createPage({
path: path,
component: blogPostTemplate,
context: {},
});
});
});
const news = graphql(`
{
news: allMarkdownRemark(
filter: { frontmatter: { layout: { eq: "news" } } }
) {
edges {
node {
frontmatter {
path
}
}
}
}
}
`).then((result) => {
if (result.errors) {
result.errors.forEach((e) => console.error(e.toString()));
return Promise.reject(result.errors);
}
const news = result.data.news.edges;
news.forEach((edge) => {
const { path } = edge.node.frontmatter;
createPage({
path: path,
component: newsTemplate,
context: {},
});
});
news.forEach(edge => {
createPage({
path: `/news/`,
component: latestNewsPage,
context: {
// This time the entire product is passed down as context
product: edge
}
});
});
});
return Promise.all([blog, news]);
};
Edit 21 November:
I replaced the above code with my attempt to use a non-static query
I added the gatsby-node config
I give here a little explanation: the BlogPost.js and NewsSingle.js are templates that create new pages for each post or news post (from Netlify CMS)
The LatestNews.js is a component in a page. This is the main page of the news. Where are shown all the news? With a static query, it works fine, however, I need to make the "limit" a variable in order to apply a load more button, that onClick will increase the limit, thus showing more news posts on the loop.
With the above configuration it says:
warning The GraphQL query in the non-page component "/home/user/projectname/src/components/pages-implementation/news/sections/LatestNews.js" will not be run.
Exported queries are only executed for Page components. It's possible you're
trying to create pages in your gatsby-node.js and that's failing for some
reason.
useStaticQuery (hence the name) does not allow to receive variables. If you take a look at the docs:
useStaticQuery does not accept variables (hence the name “static”),
but can be used in any component, including pages
The only way to pass variables in a GraphQL query is by using the context API in the gatsby-node.js. For example:
queryResults.data.allProducts.nodes.forEach(node => {
createPage({
path: `/products/${node.id}`,
component: productTemplate,
context: {
// This time the entire product is passed down as context
product: node
}
});
});
};
In the snippet above, will be a product variable in the context with the whole node. It can be accessed through pageContext prop in the destination template or used as a query parameter.

Resources