Client-Side Integration (Frontend)
8 min read
π§ββοΈ Client-Side Integration (Frontend)
Welcome back, intrepid data wrangler! So far, you've been flexing your GraphQL muscles on the server-side, defining schemas and resolvers like a seasoned architect. But what's a beautifully crafted API without a frontend to show it off? It's like a stand-up comedian with no audience β just a lot of well-structured thoughts and no one to appreciate them.
In this section, we'll bridge the gap between your powerful GraphQL server and the user's screen. We'll be using Apollo Client, the de facto standard for wrangling GraphQL data in your frontend applications. Think of it as the ultimate multitool for your data-fetching needs. It handles caching, loading states, error handling, and so much more, letting you focus on building a stellar UI.
π οΈ 1. Setting up Apollo Client in a Frontend Application
The Problem: How do we connect our frontend application to our GraphQL server and start making requests? We need a way to send queries and mutations and manage the data that comes back.
The Solution: Apollo Client! It's a comprehensive state management library for JavaScript that simplifies communication with a GraphQL server.
Let's get our hands dirty and set up Apollo Client in a React application.
Step 1: Installation π»
First things first, we need to install the necessary packages. Open your terminal in your frontend project's directory and run:
npm install @apollo/client graphqlThis command installs two key packages:
@apollo/client: The core library that contains everything we need to get started.graphql: This package provides the logic for parsing GraphQL queries.
Step 2: Initializing the Client π
Now, we need to create an instance of ApolloClient. This object is your gateway to your GraphQL server. In your application's entry point (usually index.js or main.jsx), add the following:
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
const client = new ApolloClient({
uri: 'YOUR_GRAPHQL_ENDPOINT', // Replace with your server's URL
cache: new InMemoryCache(),
});Let's break this down:
uri: This is the URL of your GraphQL server. Apollo Client needs to know where to send its requests.cache: This is an instance ofInMemoryCache. Apollo Client comes with a powerful caching system out of the box. We'll dive deeper into this later, but for now, just know that it's a magical place where your data is stored to avoid redundant network requests. β¨
Step 3: Connecting to Your React App π
The final step is to connect the client to your React component tree. We do this using the ApolloProvider component.
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://flyby-router-demo.herokuapp.com/', // A handy public GraphQL API for practice
cache: new InMemoryCache(),
});
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</React.StrictMode>
);By wrapping your App component with ApolloProvider, you're making the Apollo Client instance available to all components in your application. Now, any component can execute queries and mutations.
Interesting Fact: The InMemoryCache is surprisingly smart. It normalizes your data, meaning it stores individual objects from your queries in a flat structure. This allows it to efficiently update the cache when you refetch data or perform mutations. It's like having a hyper-organized personal assistant for your application's data.
π 2. Executing Queries and Handling Loading/Error States
The Problem: We've set up our client. Now, how do we actually fetch data from our server and display it in our components? And what happens while the data is being fetched, or if something goes wrong?
The Solution: The useQuery hook! This is the primary way to execute queries in a React component using Apollo Client.
Let's imagine we want to fetch a list of animes from our GraphQL server.
Step 1: Writing the Query βοΈ
First, we need to define our GraphQL query using the gql tag from @apollo/client.
import { gql } from '@apollo/client';
const GET_ANIMES = gql`
query GetAnimes {
animes {
id
title
episodes
}
}
`;Step 2: Using the useQuery Hook π£
Now, in our component, we can use the useQuery hook to execute this query.
import { useQuery } from '@apollo/client';
import { GET_ANIMES } from './queries'; // Assuming you saved your query in a separate file
function AnimeList() {
const { loading, error, data } = useQuery(GET_ANIMES);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<div>
{data.animes.map(({ id, title, episodes }) => (
<div key={id}>
<h3>{title}</h3>
<p>Episodes: {episodes}</p>
</div>
))}
</div>
);
}Let's dissect the magic happening here:
useQuery(GET_ANIMES): We pass our query to theuseQueryhook.loading: This is a boolean that istruewhen the query is in flight. This is perfect for showing a loading spinner or some placeholder content.error: If the query fails for any reason (network error, server error, etc.), this object will contain information about the error.data: Once the query is successful, this object will contain the data returned from the server.
This declarative approach to data fetching is a game-changer. You simply declare what data your component needs, and Apollo Client takes care of the rest, including the loading and error states. No more manually managing isLoading flags!
Funny Exaggeration: Trying to manage loading and error states manually for every network request is like trying to juggle chainsaws while riding a unicycle on a tightrope. useQuery is your safety net, your helmet, and your very sensible decision to just use a ladder instead.
π₯ 3. Firing Mutations and Updating the UI
The Problem: Fetching data is great, but what about changing it? How do we add, update, or delete data on the server and then see those changes reflected in our UI?
The Solution: The useMutation hook! Just as useQuery is for fetching data, useMutation is for sending data to the server.
Let's say we want to add a new anime to our list.
Step 1: Writing the Mutation βοΈ
First, we define our mutation using the gql tag.
import { gql } from '@apollo/client';
const ADD_ANIME = gql`
mutation AddAnime($title: String!, $episodes: Int!) {
addAnime(title: $title, episodes: $episodes) {
id
title
episodes
}
}
`;Notice that this mutation takes variables ($title and $episodes).
Step 2: Using the useMutation Hook π₯
In our component where we have a form to add a new anime, we can use the useMutation hook.
import { useMutation } from '@apollo/client';
import { ADD_ANIME, GET_ANIMES } from './queries';
import { useState } from 'react';
function AddAnimeForm() {
const [title, setTitle] = useState('');
const [episodes, setEpisodes] = useState('');
const [addAnime, { data, loading, error }] = useMutation(ADD_ANIME, {
refetchQueries: [
{ query: GET_ANIMES },
],
});
const handleSubmit = (e) => {
e.preventDefault();
addAnime({ variables: { title, episodes: parseInt(episodes) } });
setTitle('');
setEpisodes('');
};
if (loading) return 'Submitting...';
if (error) return `Submission error! ${error.message}`;
return (
<form onSubmit={handleSubmit}>
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Anime Title"
/>
<input
value={episodes}
onChange={(e) => setEpisodes(e.target.value)}
placeholder="Number of Episodes"
type="number"
/>
<button type="submit">Add Anime</button>
</form>
);
}Here's what's happening:
useMutation(ADD_ANIME): We pass our mutation to theuseMutationhook.addAnime: This is a function that we can call to trigger the mutation.{ variables: { ... } }: When we calladdAnime, we pass in the variables that our mutation expects.refetchQueries: This is one way to update the UI after a mutation. Here, we're telling Apollo Client to refetch theGET_ANIMESquery after theaddAnimemutation is complete. This ensures that our list of animes is up-to-date.
While refetchQueries is straightforward, it's not always the most efficient way to update the UI, which brings us to our next topic...
β¨ 4. The Magic of Apollo Cache: Keeping Data in Sync
The Problem: Refetching queries after every mutation can be slow and inefficient, especially for large datasets. Isn't there a smarter way to update our local data without making another network request?
The Solution: Directly manipulating the Apollo Client cache! This is where the true power and "magic" of Apollo Client shines.
Instead of refetching the entire list of animes, we can use the update function in our useMutation hook to directly write the new anime to the cache.
import { useMutation } from '@apollo/client';
import { ADD_ANIME, GET_ANIMES } from './queries';
function AddAnimeForm() {
// ... (state and other logic from the previous example)
const [addAnime] = useMutation(ADD_ANIME, {
update(cache, { data: { addAnime } }) {
const { animes } = cache.readQuery({ query: GET_ANIMES });
cache.writeQuery({
query: GET_ANIMES,
data: { animes: [...animes, addAnime] },
});
}
});
// ... (handleSubmit and JSX from the previous example)
}Let's break down this update function:
cache.readQuery({ query: GET_ANIMES }): We first read the existing animes from the cache.cache.writeQuery({ ... }): We then write the new anime to the cache by combining the existing animes with the new anime that was returned from the mutation.
By directly updating the cache, the UI will automatically re-render with the new data. This is much faster and more efficient than refetching the entire query.
Real-life Scenario: Imagine you have a shopping list on your fridge (the cache). When you buy an item (a mutation), you could drive all the way back to the store to see what you still need to buy (refetching). Or, you could simply cross the item off your list on the fridge (updating the cache). The second approach is obviously much more efficient!
This guide has provided a whirlwind tour of integrating GraphQL into your frontend with Apollo Client. We've only scratched the surface, but you now have the foundational knowledge to start building powerful, data-driven applications.
π Additional Resources
- Apollo Client Documentation: The official and most comprehensive resource. https://www.apollographql.com/docs/react/
- GraphQL Documentation: To deepen your understanding of GraphQL itself. https://graphql.org/learn/
- Fullstack Apollo React Tutorial: A great step-by-step guide to building a full application. https://www.apollographql.com/docs/tutorial/
Challenge
You are working on a to-do list application that uses Apollo Client to manage its state. The component already fetches and displays a list of to-dos. Your task is to implement the functionality to add a new to-do item.
To ensure the UI updates efficiently without extra network requests, you must manually update the Apollo Client cache after the mutation is successful.
Your Tasks:
Define the GraphQL Mutation: In the
ADD_TODOconstant, define a GraphQL mutation namedaddTodo. This mutation must accept a single variable,text(which is a non-nullableString), and return theid,text, andcompletedfields of the newly created to-do item.Implement
useMutation: In theTodoAppcomponent, use theuseMutationhook with yourADD_TODOmutation.Update the Cache: Configure the
useMutationhook with anupdatefunction. Inside this function, you must:- Read the existing to-do list from the cache for the
GET_TODOSquery. - Append the new to-do item (returned from the mutation) to this list.
- Write the updated to-do list back to the cache for the
GET_TODOSquery.
- Read the existing to-do list from the cache for the
Constraint: You must not use the refetchQueries option.
Expected result
Your completed code should satisfy the following criteria:
- The
ADD_TODOconstant must contain a valid GraphQL mutation string. - The mutation definition must be named
addTodoand accept a$textvariable of typeString!. - The mutation must specify
id,text, andcompletedin its return fields. - The
useMutationhook must be called withADD_TODOand an options object. - The options object must contain an
updatefunction. - Inside the
updatefunction,cache.readQuerymust be called with theGET_TODOSquery to retrieve the current cache state. - Inside the
updatefunction,cache.writeQuerymust be called to update the cache for theGET_TODOSquery with a newtodosarray that includes the new to-do item returned from the mutation.