I wrote a query of GraphQL.
import { gql } from '#apollo/client';
export const GET_CART_DETAILS_QUERY = gql`
query GetProductSizeChartQuery($sku:String!) {
getProductSizeChart(sku:$sku){
heading:{
label
values: {
sku
attribute_id
size_id
size
is_stock
}
}
sizeChart:{
title
options:{
inch
cm
}
}
optionLabel:{
label
}
}
}
`;
And I am calling it as :
const {
data: ProductSizeChartData,
loading: ProductSizeChartLoading,
error: ProductSizeChartError
} = useQuery(GET_CART_DETAILS_QUERY, {
variables: { sku: item?.product?.sku }
});
But I am getting an error :
Syntax Error: Expected Name, found "{".
I am not able to detect what is wrong here. Please help !
Related
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");
}
I want to make parameterized requests from the Apollo client to the Apollo server.
On client:
const GET_VALUES = gql`
query Values($desc: String!) {
Values
}
`;
function ValueSelector({ pickValue, dirDesc }) {
const { loading, data, error } = useQuery(GET_VALUES, {
variables: { dirDesc },
});
}
On server (schema):
type Query {
Values(desc: String!): [String]
#cypher(
statement: "MATCH (:Dir{description:$desc})-[:value]->(v) RETURN collect(v.TXTLG)"
)
}
Result:
[GraphQL error]: Message: Field "Values" argument "desc" of type "String!" is required, but it was not provided., Location: [object Object], Path: undefined
[Network error]: ServerError: Response not successful: Received status code 400
You should use desc instead of dirDesc in variables param of useQuery. Try this:
const { loading, data, error } = useQuery(GET_VALUES, {
variables: { desc: dirDesc },
});
const GET_VALUES = gql`
query Values($desc: String!) {
Values(desc: $desc)
}
`;
function ValueSelector({ pickValue, dirDesc }) {
const { loading, data, error } = useQuery(GET_VALUES, {
variables: { desc:dirDesc},
});
Your query declaration on the client is missing the actual variable. It should be something like this
const GET_VALUES = gql`
query Values($desc: String!) {
Values(dirDesc: $desc)
}
`;
Then you can use useQuery passing dirDesc.
I am using Gatsby and GraphQL, and I am new to GraphQL.
I have the following schema definition:
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type MarkdownRemark implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
title: String!
products: [Product]
}
type Product #dontInfer {
name: String!
price(price: Int = 1): Float
description: String
images: [ProductImage]
}
type ProductImage {
url: String
}
`;
createTypes(typeDefs);
};
Then on my page I use the following query:
query {
markdownRemark(fileRelativePath: { eq: "/content/pages/products.md" }) {
...TinaRemark
frontmatter {
title
products {
name
price
description
images {
url {
childImageSharp {
fluid(maxWidth: 1920) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
}
}
html
}
}
I then receive the following error:
Field "url" must not have a selection since type "String" has no subfields.
Does anyone have any suggestions on how to work around this error?
Also, what is childImageSharp? I'm wondering what the terminology is to define it. Is it a GraphQL "selector" or "function"?
It should be
query {
markdownRemark(fileRelativePath: { eq: "/content/pages/products.md" }) {
...TinaRemark
frontmatter {
title
products {
name
price
description
images {
url
}
}
}
html
}
}
Because you definition is
type ProductImage {
url: String
}
The url apparently has no sub fields.
For what it's worth (I don't know if this is related to your specific issue.) If your markdown path for the image file is invalid, GraphQL will return this error, interpreting the path as a string. I had this problem and it went away when I realized I had misspelled the path in the markdown.
productImage {
childImageSharp {
gatsbyImageData(width: 200)
}
}
I had a similar problem with returning a boolean. For me, instead of something like this
mutation {
someFunc(
memo: "test memo"
) {
success
}
}
I needed this
mutation {
someFunc(
memo: "test memo"
)
}
I'd like to do something like the following so I can get Gatsby Images dynamically:
const image = 'gastby-astronaut.png';
export const imageQuery = graphql`
{ allImageSharp (
filter: {
fluid: {
originalName: {
regex: "/${image}/"
}
}
}
){
edges {
node {
fluid {
originalName
}
}
}
}
}
`;
However, I can't figure out how to connect this query to an initial query that would get the 'gatsby-astronaut.png', or perform this query from a subcomponent with a . I get this error when I try this:
Error: BabelPluginRemoveGraphQL: String interpolations are not allowed
in graphql fragments. Included fragments should be referenced as
`...MyModule_foo`.
Any suggestions on the proper way to return Gatsby Images dynamically?
Ah, yeah Gatsby extracts GraphQL queries from your pages through static analysis: they load the file as text, parse it, and extract the query, all before the actual file gets executed. This means that your typical tagged-template literal functionality isn't there.
The only way to filter is through context provided when createPage is called from gatsby-node.js. I.e. if you do this:
exports.createPages = ({ graphql, actions }) =>
graphql(`some query here`).then(result => {
actions.createPage({
path: "/output-path/",
component: path.resolve(`./src/templates/your_template.jsx`),
context: { image: result.data.yourImage },
})
})
Then you can do this in your page query:
query SomePage($image: String!) {
allImageSharp (
filter: {
fluid: {
originalName: {
regex: $image
}
}
}
){
edges {
node {
fluid {
originalName
}
}
}
}
}
Here's a solution I came up with... pretty janky, but it works:
import PropTypes from 'prop-types';
import React from 'react';
import Img from 'gatsby-image';
import { useStaticQuery, graphql } from 'gatsby';
const Image = ({ imageYouWant }) => {
const data = useStaticQuery(
graphql`
query allTheImagesQuery{
allImageSharp {
edges {
node {
fluid(maxWidth:1000) {
...GatsbyImageSharpFluid
originalName
}
}
}
}
}`,
);
const TheImageYouWant = data.allImageSharp.edges
.filter(edge => edge.node.fluid.originalName === imageYouWant)
.map(myImage => <Img fluid={myImage.node.fluid} />);
return (
<>
{ TheImageYouWant }
</>
);
};
Image.propTypes = {
imageYouWant: PropTypes.string,
};
Image.defaultProps = {
imageYouWant: '',
};
export default Image;
I'm trying to run the following graphql query but the terminal is saying I have syntax errors in my code:
export const query = graphql`
query allAirtableLinked(filter: { table: { eq: "Published" } }) {
edges {
node {
id
data {
title
}
}
}
}
`
Terminal declares a syntax error
Error: BabelPluginGraphQL: GraphQL syntax error in query:
query allAirtableLinked(filter: {table: {eq: "Published"}}) {
edges {
node {
id
data {
title
}
}
}
}
message:
Syntax Error GraphQL request (4:27) Expected $, found Name "filter"
3:
4: query allAirtableLinked(filter: {table: {eq: "Published"}}) {
^
5: edges {
Any ideas?
You're passing arguments to the GraphQL query object and not the query field.
Try something like this:
query allAirtableLinked($filter: { table: { eq: "Published" } }) {
allAirtableLinked(filter: $filter) {
edges {
node {
id
data {
title
}
}
}
}
}