concept Apollo Client in category graphql

This is an excerpt from Manning's book GraphQL in Action.
These reasons are why specialized front-end GraphQL client libraries exist. In the next chapter, we will explore one of the most popular clients today: The Apollo Client.
Listing 10.2. New code in
web/src/index.js| Initializing and using Apollo Clientimport { ApolloClient, HttpLink, InMemoryCache, gql, } from '@apollo/client'; import * as config from './config'; const cache = new InMemoryCache(); const httpLink = new HttpLink({ uri: config.GRAPHQL_SERVER_URL }); const client = new ApolloClient({ cache, link: httpLink }); async function main() { const { data, errors } = await client.query({ query: gql` query { numbersInRange(begin: 1, end: 100) { sum } } `, }); console.log({ data, errors }); } main();This is the simplest example for using Apollo Client in plain JavaScript but it already introduces many new concepts. Let’s walk through them:
Apollo Client issued only ONE Ajax request for both query operations because the response of the first request was automatically cached (in memory) and Apollo Client figured out that there is no need to go ask the server again for the same data that we already have.
This is a simple example, but Apollo Client does a lot of heavy lifting under the hood to make the cache as useful as it can be. For example, it caches every data response in a flattened data structure so that it can use the cache of individual objects to determine what future network requests are needed, even for different queries. For example, make the following changes in
web/src/index.js:Listing 10.4. Repeating a partial query
async function main() { const resp1 = await client.query({ query: gql` **{ taskMainList { id content tags createdAt } }** `, }); console.log(resp1.data); const resp2 = await client.query({ query: gql` **{ taskMainList { content } }** `, }); console.log(resp2.data); }This code asks to send two different query operations to the server. However, because the second one is a subset of the first one, Apollo Client would still not go to the server a second time!
Figure 10.3. Output of the partial query code
![]()
While this is already impressive, wait until you see the other features offered by Apollo Client (caching and otherwise). Let me give you another example, but this time with a mutation operation.
Apollo Client is flexible. It offers many methods to invoke queries on-render, on-demand, or conditionally. You can use different types of caching stores. You can modify request headers globally or per operation. You can skip queries and instruct Apollo not to cache them if needed. You can have it communicate with multiple GraphQL services and use the same store for them. You can even use it to communicate with REST-based API services.