JAVASCRIPT
Integrate GraphQL with React using Apollo Client
Seamlessly integrate GraphQL APIs into your React application using Apollo Client. Learn to perform queries and display data from your GraphQL endpoint efficiently.
import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql } from '@apollo/client';
// 1. Initialize Apollo Client
const client = new ApolloClient({
uri: 'https://rickandmortyapi.com/graphql', // Example GraphQL API endpoint
cache: new InMemoryCache(),
});
// 2. Define your GraphQL query
const GET_CHARACTERS = gql`
query GetCharacters {
characters {
results {
id
name
species
image
}
}
}
`;
// 3. React Component to display data
function CharactersList() {
const { loading, error, data } = useQuery(GET_CHARACTERS);
if (loading) return <p>Loading characters...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h2>Rick and Morty Characters</h2>
<ul>
{data.characters.results.map(({ id, name, species, image }) => (
<li key={id}>
<h3>{name}</h3>
<p>Species: {species}</p>
<img src={image} alt={name} style={{ width: '100px', height: '100px' }} />
</li>
))}
</ul>
</div>
);
}
// 4. Wrap your App with ApolloProvider
function App() {
return (
<ApolloProvider client={client}>
<CharactersList />
</ApolloProvider>
);
}
export default App;
How it works: This React snippet demonstrates how to integrate a GraphQL API using Apollo Client. First, an `ApolloClient` instance is initialized with the GraphQL endpoint and an `InMemoryCache`. Next, a GraphQL query, `GET_CHARACTERS`, is defined using the `gql` tag. The `CharactersList` component then uses the `useQuery` hook from Apollo Client to execute this query, handling loading, error, and data states automatically. Finally, the entire application or relevant part is wrapped with `ApolloProvider`, making the client accessible to all child components. This setup provides a powerful and efficient way to fetch and manage data from GraphQL APIs in React applications.