In this tutorial, we will learn how to fetch data from a GraphQL API using queries with Apollo Client. By the end of this tutorial, you should be able to write and send GraphQL queries to fetch data from an API.
Prerequisites
You should have a basic understanding of JavaScript, Node.js, and have Apollo Client installed in your working environment.
GraphQL is a data query language and runtime designed and used to request and deliver data to mobile and web apps. In GraphQL, you structure your data in the way you want it to be. Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL.
Writing GraphQL Queries
A GraphQL query is used to read or fetch values. It returns exactly what a client asks for and nothing more. Here's a basic example of a GraphQL query:
query {
posts {
title
author
}
}
This query fetches all posts with their titles and authors.
Sending GraphQL Queries With Apollo Client
The Apollo Client has its own function to send queries, called useQuery
. It is a React Hook that fetches data in a declarative way.
Example 1: Setting Up Apollo Client
Before sending queries, we need to set up the Apollo Client in our app.
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql', // replace with your GraphQL API URI
cache: new InMemoryCache()
});
This sets up an Apollo Client that connects to your GraphQL API.
Example 2: Sending a GraphQL Query
Here's how you would use the useQuery
function to send a query.
import { useQuery, gql } from '@apollo/client';
const GET_POSTS = gql`
query GetPosts {
posts {
title
author
}
}
`;
function Posts() {
const { loading, error, data } = useQuery(GET_POSTS);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
return data.posts.map((post) => (
<div key={post.id}>
<p>{post.title}</p>
<p>{post.author}</p>
</div>
));
}
In this example, we define our GraphQL query with the gql
function, and then use the useQuery
hook to send the query. The useQuery
hook returns an object from Apollo Client that contains loading, error, and data properties you can use to render your UI.
In this tutorial, we've learned how to fetch data from a GraphQL API using queries with Apollo Client. We learned how to write GraphQL queries and how to use Apollo Client's useQuery
function to send these queries.
For further learning, you can explore more about GraphQL mutations (how to modify data) and subscriptions (real-time updates).
Exercise 1:
Write a GraphQL query to fetch a single post with its title, author, and comments.
Exercise 2:
Modify the Posts component to use the query from Exercise 1. Display the post's title, author, and comments.
Exercise 3:
Add error handling to the Posts component. If the query returns an error, display an error message.
Explore the Apollo Client documentation for more information and examples.