Graphql gql with variables and Query component (deprecated) - reactjs

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 {
…
}
}
}

Related

Showing bad request while fetching data using graphQl?

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

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.

Passing ID in GraphQL query not returning data

so i'm trying to use Apollo GraphQL with React to get specific product data by its ID, but it seems to be returning undefined. I read the Apollo docs and researched, so I'm not sure what I'm doing wrong. Also, I'm able to return data from other queries that don't require an ID (like all products, for instance). Would greatly appreciate some help!
Query
export const PRODUCT = gql`
query GetProduct($itemID: String!) {
product(id: $itemID) {
id
name
inStock
gallery
description
category
attributes {
id
name
type
items {
displayValue
value
}
}
prices {
currency {
label
symbol
}
}
brand
}
}
`;
This is where I try to return data using the ID, but to no avail:
let myID = "ps-5";
const { productLoading, productError, productData } = useQuery(PRODUCT, {
variables: { itemID: myID },
});
useEffect(() => {
if (productData) {
console.log("data: " + productData) // logs nothing. "Undefined" when if statement is removed
}
}, [])
It looks like the React client for Apollo uses the same API for useQuery as for Vue (with which I'm more familiar), in which case it should be used like this:
useQuery(PRODUCT, { itemID: myID })
(not { variables : { itemID : myID }})
I would have expected the backend to return an error though, because $itemID is declared as non-nullable.
It seems that you are destructing the object that useQuery() returns with the wrong object keys.
// instead of
const { productLoading, productError, productData } = '...'
// you can either use the regular keys as variables
const { loading, error, data } = '...'
// or assign aliases (useful when you use more queries on the same page)
// this way you can use the same variables as in your example
const { loading:productLoading, error:productError, data:productData } = '...'

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/

Dynamic filter operator in GraphQL using Apollo (in a React app)

I'm using Apollo to make requests to my GraphQL server.
My query is like below:
export const QUERY_ITEMS = gql`
query get_items($date: date) {
items(where: {date: {_eq: $date}}) {
name
}
}
`;
const {data} = useQuery(QUERY_ITEMS, variable: {date: '2020-01-01'});
Notice how right now the _eq operator is hardcoded. I'm implementing a feature where I'm making that operator dynamic to enable things like '_gt' and '_lt' .How can I achieve this?
gql can receive placeholder variable
function gql(literals: any, ...placeholders: any[]): any;
so you can use something like this
export const QUERY_ITEMS = (placeholder) => gql`
query get_items($date: date) {
items(where: {date: {${placeholder}: $date}}) {
name
}
}
`;
Rather than passing in the date as a variable, you can pass in the entire expression
query get_items($exp: SomeType) {
items(where: { date: $exp }) {
name
}
}
or the entire argument
query get_items($where: SomeOtherType) {
items(where: $where) {
name
}
}
The types you use for your variable are schema-specific -- you can look up information about the schema Hasura generates in the GraphiQL interface available through the console (just search for the field name).

Resources