The Apollo Client package for React has a handy hook called useQuery
. It is the primary API used to execute queries in an Apollo application.
Here is the useQuery
hook used in a simple React application that queries a list of cars and displays their make and model.
import client from "client"; import { ApolloProvider } from "@apollo/client"; import Cars from "components/Cars"; function App() { return ( <div className="my-4 mx-auto px-4"> <ApolloProvider client={client}> <Cars /> </ApolloProvider> </div> ); } export default App;
useQuery
Here is a list of options that we can pass to useQuery
. For a complete list, visit the
query
: This is a GraphQL query.
variables
: This is an object that contains GraphQL queries required to execute a query.
errorPolicy
: This specifies error handling for errors given by GraphQL.
onCompleted
: This is a callback function that executes on successful execution of the query.
onError
: This is a callback function that executes if the query results in an error.
Try experimenting with these options in the playground below. In the below widget, useQuery
is being used in the WrappedCars
function.
import client from "client"; import { ApolloProvider } from "@apollo/client"; import Cars from "components/Cars"; function App() { return ( <div className="my-4 mx-auto px-4"> <ApolloProvider client={client}> <Cars /> </ApolloProvider> </div> ); } export default App;
Free Resources