JAVASCRIPT

Efficiently Querying GraphQL APIs with Apollo Client

Learn how to integrate and query a GraphQL API in a React application using Apollo Client, focusing on data fetching and state management.

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. 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 application with ApolloProvider
export default function App() {
  return (
    <ApolloProvider client={client}>
      <ContinentsList />
    </ApolloProvider>
  );
}
How it works: This snippet demonstrates how to integrate with a GraphQL API using Apollo Client in a React application. It involves initializing the `ApolloClient` with the API URI and a cache, defining a GraphQL query using `gql` tag, and then using the `useQuery` hook within a React component to fetch and display data. The `ApolloProvider` wraps the application to make the client available throughout the component tree, simplifying data fetching and state management for GraphQL interactions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs