JAVASCRIPT
Consuming a GraphQL API with Apollo Client (React)
Integrate a GraphQL API into your React application using Apollo Client, performing queries and displaying data efficiently.
import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql } from '@apollo/client';
// 1. Initialize Apollo Client
const client = new ApolloClient({
uri: 'https://graphqlzero.almansi.me/api', // Example public GraphQL API
cache: new InMemoryCache(),
});
// 2. Define your GraphQL query
const GET_TODOS = gql`
query GetTodos {
todos(options: { limit: 5 }) {
data {
id
title
completed
}
}
}
`;
// 3. Create a React Component to use the query
function TodosList() {
const { loading, error, data } = useQuery(GET_TODOS);
if (loading) return <p>Loading todos...</p>;
if (error) return <p>Error :( {error.message}</p>;
return (
<div>
<h2>My Todos</h2>
<ul>
{data.todos.data.map(({ id, title, completed }) => (
<li key={id} style={{ textDecoration: completed ? 'line-through' : 'none' }}>
{title}
</li>
))}
</ul>
</div>
);
}
// 4. Wrap your App with ApolloProvider
function App() {
return (
<ApolloProvider client={client}>
<TodosList />
</ApolloProvider>
);
}
// export default App; // In a real app, you'd export this App component
How it works: This snippet demonstrates how to integrate a GraphQL API into a React application using Apollo Client. It starts by initializing `ApolloClient` with the GraphQL endpoint and a cache. Then, it defines a GraphQL query using the `gql` tag. Inside a React functional component, `useQuery` hook fetches data, managing loading and error states. Finally, the entire application is wrapped with `ApolloProvider` to make the client available to all components. This offers a powerful and type-safe way to manage data fetching for complex applications.