JAVASCRIPT
Fetching Data from GraphQL API using Apollo Client in React
Integrate a GraphQL API into a React application using Apollo Client, demonstrating how to set up the client, define queries, and display data.
// Install: npm install @apollo/client graphql
import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery } from '@apollo/client';
// 1. Initialize Apollo Client
const client = new ApolloClient({
uri: 'https://countries.trevorblades.com/', // Example public GraphQL API
cache: new InMemoryCache(),
});
// 2. Define your GraphQL query
const GET_CONTINENTS = gql`
query GetContinents {
continents {
code
name
}
}
`;
// 3. Create a React component to display data
function ContinentsList() {
const { loading, error, data } = useQuery(GET_CONTINENTS);
if (loading) return <p>Loading continents...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h2>Continents</h2>
<ul>
{data.continents.map(({ code, name }) => (
<li key={code}>
{name} ({code})
</li>
))}
</ul>
</div>
);
}
// 4. Wrap your App with ApolloProvider
function App() {
return (
<ApolloProvider client={client}>
<h1>My GraphQL App</h1>
<ContinentsList />
</ApolloProvider>
);
}
export default App;
How it works: This React snippet illustrates how to integrate with a GraphQL API using Apollo Client. It first initializes an `ApolloClient` instance pointing to a GraphQL endpoint. Then, it defines a GraphQL query using the `gql` tag. The `useQuery` hook is utilized within a functional component to execute the query, providing `loading`, `error`, and `data` states, making it easy to manage the asynchronous data fetching process and render content conditionally based on the API response.