Writing GraphQL Queries
Explore how to write GraphQL queries and execute them within React components using Apollo Client. Learn to use the useQuery hook to fetch data, handle loading and error states, and separate data fetching logic into pure components for reusable and testable code.
We'll cover the following...
Changing the code files
At this point, we know that we have data in a GraphQL server. We also know that we can write a GraphQL query to get that data. We haven’t yet seen how to write a GraphQL query and execute it in the context of a component. That’s what we will be doing in this lesson.
Make a GraphQL query
Let’s start with how to write a GraphQL query. To accomplish this, we'll need to import a particular package that will allow us to write these queries in our components/Books/index.tsx file.
import { gql } from "graphql-tag";
Once this package has been imported, we can use it, as shown like in the code snippet below.
const allBooksQuery = gql`query allBooks {books {title}}`;
The variable allBooksQuery holds our GraphQL query, but it won’t ...