...

/

Sending GraphQL Queries with Apollo Client

Sending GraphQL Queries with Apollo Client

Learn how to send GraphQL queries in React applications using Apollo Client.

Now that we’ve covered the structure of our frontend application, it’s time to learn how to fetch and display data from the GraphQL API. We’ll start by using the allProducts query, which returns all the products in our application. Later on, we’ll cover advanced topics such as passing arguments, using fragments, and executing mutations.

We’ll also learn how to use regular and lazy queries with Apollo Client. We’ll also briefly go over React hooks, which are a feature that the Apollo library uses extensively.

Before we start

Before starting this section, we need to make a small change to the GraphQL schema on the server and add the id field to the Product type.

Press + to interact
type Product {
id: String!,
...
}

We don’t need to change any resolvers because the id property is already returned with every object Mongoose returns. We just weren’t exposing it before.

The primary purpose of this field is to provide a unique key value when rendering multiple React objects, like we discussed in the previous lesson.

Now, we can go back to implementing the frontend.

Adding GraphQL to the project

We need to add the Apollo Client library to our project. This client-side library from Apollo allows us to interact with a GraphQL API. To add it to the project, we need to install it using npm.

npm install @apollo/client

Now, we need to configure Apollo Client in our application. To do this, we create an instance of the ApolloClient class and configure it to use our GraphQL backend.

Press + to interact
// index.js
import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client'
const client = new ApolloClient({
cache: new InMemoryCache(),
uri: 'http://localhost:3000/graphql'
})

We’ll pass two parameters to the constructor:

  • uri:
...