Showing bad request while fetching data using graphQl? - reactjs

The getProductById is in another js file. When I am trying to use this by putting some static id in gql playground, it is working,
export const getProductById = gql`
query getProductById($id: String!) {
product(id: $id) {
id
brand
name
gallery
inStock
prices {
currency
amount
}
category
description
attributes {
id
name
type
items {
displayValue
value
id
}
}
}
}
`;
const{data, loading, error} = useQuery(getProductById,{
variables:{id}
})
When I am consoling log data it is showing undefined.
It is also returning error which is
Error: Response not successful: Received status code 400

Related

Graphql gql with variables and Query component (deprecated)

I am trying to get use graphql with query component .
const LOAD_PRODUCTS = gql`
query {
category(input :{title : "${category}"}){
name
products {
id
name
brand
inStock
gallery
prices{
currency {
label
symbol
}
amount
}
attributes{
id
name
type
items {
id
displayValue
value
}
}
}
}
}
`
and later i am using the query compnent to fetch the data
<Query query={LOAD_PRODUCTS} variables={{category : "all" }}></Query>
but react is give error that category is not defined in the gql
what to do ....
I tried all the solutions on the internet and failed.
I did not want to use the hooks.
You need to specify the mapping of your query variables. Also your syntax is assuming string substitution rather than query variables.
Try:
const LOAD_PRODUCTS = gql`
query myQuery ( $category: String! ) {
category(input: { title: $category }){
name
products {
…
}
}
}

use graphql query and mutation in same file

const QUERIES = gql`
query {
getGrades {
grade_info
id
}
getSubjects {
id
subject_info
}
getSchools {
school_name
id
}
}
`;
const MUTATIONS = gql`
mutation {
createTeacher(
first_name: ${firstName}
last_name: ${lastName}
phone: "${number}
email: ${email}
subjectRef: ["6287323efe0b204eee241cc5"]
gradeRef: ["62872b8b0023e0dcc9c5a703"]
schoolRef: "62ab59edde044d104f10e5a9"
) {
id
first_name
last_name
phone
email
email_verified
approved
number_verified
}
}
`;
const { loading, error, data } = useQuery(QUERIES);
const [mutateFunction, { data, loading, error }] = useMutation(MUTATIONS);
Here is my graphql query using in react .
But my data variable conflicting in query and mutation
How to handle the situation ?
Please take a look .
If am changing data to something else it is not working.
You are using a destructuring assignment in order to extract the fields data, error, loading from the response of useQuery and useMutation.
The destructuring assingment operator allows renaming the variables (please find better variable names than I used as an example ;-) )
Example:
const { loading: loadingQueries, error: errorQueries, data: dataQueries } = useQuery(QUERIES);
//use
console.log(loadingQueries);
The same can be applied for useMutation.

GraphQL on component load, Query will sometimes return populated properties as null

I am using graphQl with react with apollo client and mongoose. Sometimes when I click on a component. rand om data will return from this useQuery as null.
// must define novel as a state to use useEffect correctly
const [novel, setNovel] = useState({});
const { loading, data } = useQuery(GET_NOVEL, {
variables: { _id: novelId }
});
// use effect ensures that all novel data is completely loaded
// before rendering the SingleNovel page
useEffect(() => {
console.log(data?.novel);
// if there's data to be stored
if (data) {
setNovel(data.novel)
}
}, [data, loading, novel]);
export const GET_NOVEL = gql`
query getNovel($_id: ID!) {
novel(_id: $_id) {
_id
title
description
penName
user {
_id
username
email
}
favorites{
_id
}
createdAt
reviews {
_id
reviewText
rating
createdAt
user{
_id
username
}
}
chapterCount
reviewCount
}
}
`
Specifically, the novel.user.username and reviews.rating property come back as null. On reload of the page however, the data seems to populate the fields normally.
How can I fix this?
Heres the resolver
novel: async (parent, { _id }) => {
// returns single novel from the novel id given
const novel = await Novel.findOne({ _id })
.populate('user')
// populate the reviews for the novel but also populate
// the info within the reviews of the user who made each review.
.populate({
path: 'reviews',
populate: {path: 'user'}
})
.exec();
console.log(novel)
return novel;
},

Nested graphql query

I am pretty new with graphql , I don't know how to apply this filter.
following is schema
const GET_TICKETS = gql`
query Ticket($filter: String) {
tickets(filter: $filter) {
id
title
firstname
lastname
gender
contactnumber
email
address
pincode
location
emergency_type
priority
descriptionof_assistance
date_created
status
work_items {
id
status
service
volunteers {
volunteer_id
volunteer_name
status_of_acceptance
}
}
}
}
`;
I want to fetch all tickets where workitems contain given volunteer
fetch tickets where volunteer in workitems.volunteers ....something like this
When you use useQuery There is an optional second parameter or useLazyQuery on the function trigger.
Example from the official documentation.
useQuery
const { loading, error, data } = useQuery(GET_DOG_PHOTO, {
variables: { breed },
});
So on your case it should be
const { loading, error, data } = useQuery(GET_TICKETS, {
variables: { filter: "the filter value" },
});
and on useLazyQuery will look like this:
const [getTickets, { loading, error, data }] = useLazyQuery(GET_TICKETS);
//..... somewhere else
getTickets({variables: {filter: "filter value"}})
reference: https://www.apollographql.com/docs/react/data/queries/

GraphQLError: Syntax Error: Expected Name, found }

I'm trying to format my GraphQL query using fragments, but I keep getting the error:
GraphQLError: Syntax Error: Expected Name, found }
const ItemFields = gql`
fragment ItemFields on Item {
id
title
imageurl
description
createdon
tags {
id
title
}
ownerid {
id
fullname
email
bio
}
borrower {
id
fullname
email
bio
}
}
`;
export const ALL_ITEMS_QUERY = gql`
query item($filter: ID) {
item {
...ItemFields
}
}
${ItemFields}
`;
Has anyone encountered a similar issue? Can anyone advise me how to correct this?

Resources