Introduction
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. It helps you fetch, cache, and modify application data, all while automatically updating your UI.
Key Features of Apollo Client:
- Declarative Data Fetching: Write queries directly within your components.
- Normalized Caching: Efficiently cache and manage data.
- State Management: Manage local and remote data seamlessly.
- Developer Tools: Powerful tools for debugging and optimizing your GraphQL queries.
Setting Up Apollo Client
Step 1: Install Apollo Client
To get started, you need to install the necessary packages. You can do this using npm or yarn.
or
Step 2: Initialize Apollo Client
Create an instance of Apollo Client and provide it with the URL of your GraphQL server.
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://your-graphql-endpoint.com/graphql',
cache: new InMemoryCache()
});Step 3: Integrate Apollo Client with React
To use Apollo Client with React, you need to wrap your application with the ApolloProvider component.
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider } from '@apollo/client';
import App from './App';
import client from './apolloClient'; // Import the client instance
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root')
);Fetching Data with Queries
Writing a Query
Define your GraphQL query using the gql template literal.
import { gql } from '@apollo/client';
const GET_USERS = gql`
query GetUsers {
users {
id
name
email
}
}
`;Executing a Query
Use the useQuery hook to execute the query within a React component.
import React from 'react';
import { useQuery } from '@apollo/client';
import { GET_USERS } from './queries';
const Users = () => {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.users.map(user => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
);
};
export default Users;Modifying Data with Mutations
Writing a Mutation
Define your GraphQL mutation using the gql template literal.
import { gql } from '@apollo/client';
const ADD_USER = gql`
mutation AddUser($name: String!, $email: String!) {
addUser(name: $name, email: $email) {
id
name
email
}
}
`;Executing a Mutation
Use the useMutation hook to execute the mutation within a React component.
import React, { useState } from 'react';
import { useMutation } from '@apollo/client';
import { ADD_USER } from './mutations';
const AddUser = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [addUser, { data, loading, error }] = useMutation(ADD_USER);
const handleSubmit = (e) => {
e.preventDefault();
addUser({ variables: { name, email } });
};
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button type="submit">Add User</button>
{data && <p>User added: {data.addUser.name}</p>}
</form>
);
};
export default AddUser;Practical Exercise
Exercise: Fetch and Display a List of Posts
- Define the Query: Create a new file
queries.jsand define a query to fetch posts. - Create the Component: Create a new component
Posts.jsto fetch and display the list of posts. - Integrate the Component: Use the
Postscomponent in your main application.
Solution
queries.js
import { gql } from '@apollo/client';
export const GET_POSTS = gql`
query GetPosts {
posts {
id
title
content
}
}
`;Posts.js
import React from 'react';
import { useQuery } from '@apollo/client';
import { GET_POSTS } from './queries';
const Posts = () => {
const { loading, error, data } = useQuery(GET_POSTS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.posts.map(post => (
<li key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</li>
))}
</ul>
);
};
export default Posts;App.js
import React from 'react';
import Posts from './Posts';
const App = () => {
return (
<div>
<h1>Posts</h1>
<Posts />
</div>
);
};
export default App;Conclusion
In this section, you learned how to set up Apollo Client, fetch data using queries, and modify data using mutations. You also practiced these concepts by creating a component to fetch and display a list of posts. In the next module, we will explore more advanced features of Apollo Client, such as caching strategies and state management.
