How can I pass an argument to useQuery when using react-apollo-hook?
This does not work:
const { data, loading, error } = useQuery(GET_DATA,
{ variables: { id: 'testId' }});
And the query itself:
export const GET_DATA = gql`
{ query ($id: String) {
document(id: $uid) {
uid
}
}
}
`;
We run a query within a React component by calling useQuery and passing it our GraphQL query string. This makes running queries from React components a breeze. When our component renders, useQuery returns an object from Apollo Client that contains loading , error , and data properties that we can use to render our UI.
The useQuery React hook is the primary API for executing queries in an Apollo application. To run a query within a React component, call useQuery and pass it a GraphQL query string.
It uses React's render props pattern. import React from "react"; import { Query } from "react-apollo"; import gql from "graphql-tag"; const GET_TODOS = gql` { todos { id type } } `; const Todos = () => ( <Query query={GET_TODOS}> {({ loading, error, data }) => { if (loading) return <p>Loading...
import { useMutation } from "@apollo/client"; We are importing the useMutation React hook from @apollo/client and the graphql query we defined above to fetch the todo data. }; In the useMutation React hook defined above, the first argument of the result tuple is the mutate function; (addTodo) in this case.
Your query is not valid because 1) it's wrapped in an extraneous pair of curly brackets and 2) you reference a variable named uid
, while the variable you defined is actually called id
. Corrected, this query would look like:
query ($id: String) {
document(id: $id) {
uid
}
}
Keep in mind, I don't know what your actual schema is so this query could still be invalid if any of the fields or arguments do not exist or are of the wrong type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With