GraphQL Using Apollo Client
Apollo Client is a JavaScript library for managing state. It helps you handle data from both local and remote sources using GraphQL. You can use it to fetch, store, and update data, and it will automatically refresh your UI.
With Apollo Client, you can structure your code declaratively, aligning with modern development practices and ensuring project consistency. It provides built-in integration with React using @apollo/client library and community integration with popular front-end frameworks (Angular, Vue), Web components (Apollo Elements), and native mobile.
Core Apollo Client Offerings
Queries
useQuery – a primary API for executing queries using Apollo Client
(https://graphql.org/learn/queries/)
Mutations
Whenever an application needs to modify data (CRUD) on the data source, we use GraphQL mutations. To do this, import useMutation from Apollo Client and call the mutation function to update the state.
Caching
When a GraphQL query is executed, the client sends it to the server and waits for a response. If the result is already in the cache, the client retrieves it from there instead. Caching improves performance by reducing network requests and traffic.
To set up the Apollo Client cache, create a new instance of the InMemoryCache class and pass it to the ApolloClient constructor.
Few caching options:
- typePolicies : it offers custom merge functions for specific data
- addTypename: it adds __typename field to every object in the cache. It is useful in debugging
The caching options list is quite long. You can view more options here.
Getting started Apollo client with React App
This blog mainly covers Apollo Client, so it doesn’t include details about Apollo Server. However, I’ve created a GitHub repository for Apollo Server that you can clone and run locally.
For Apollo Client, you can find the repository here. These resources should help you quickly grasp the basic concepts without hassle.
For the client setup, you’ll need VS Code. For the server setup, you’ll need Visual Studio Express Edition.
Additionally, make sure Node.js is installed on your machine.
Setup 1 – Setup
Open the command prompt and do the following:
npx create-react-app graphql-client
cd graphql-client
npm start
Step 2: Install Dependencies
npm install @apollo/client graphql
Step 3: Initialize ApolloClient
In Index.js, add following:
import { ApolloClient, InMemoryCache, ApolloProvider } from ‘@apollo/client’;
You’ll need to initialize the Apollo Client by providing two pieces of information.
- Uri (URI of the Apollo Server)
- Cache – Apollo client cache the results after fetching
In Index.js, add following
const client = new ApolloClient({
uri: ‘https://localhost:44318/graphql/’,
cache: new InMemoryCache(),
});
That’s it! Apollo Client is ready to fetch the data.
You can explore popular CRUD operations using GraphQL by cloning the Apollo Client repository from here.