JAVASCRIPT

Query a GraphQL API Using Apollo Client in React

Learn to integrate and query a GraphQL API efficiently within a React application using Apollo Client, simplifying data fetching and state management for complex UI needs.

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 GraphQL API endpoint
  cache: new InMemoryCache(),
});

// 2. Define your GraphQL query
const GET_COUNTRIES = gql`
  query GetCountries {
    countries {
      code
      name
      continent {
        name
      }
    }
  }
`;

// 3. Create a React Component that uses the query
function CountriesList() {
  // The useQuery hook executes your query and manages loading/error states
  const { loading, error, data } = useQuery(GET_COUNTRIES);

  if (loading) return <p>Loading countries...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h2>Countries</h2>
      <ul>
        {data.countries.map((country) => (
          <li key={country.code}>
            {country.name} ({country.code}) - {country.continent.name}
          </li>
        ))}
      </ul>
    </div>
  );
}

// 4. Wrap your application with ApolloProvider
// This makes the Apollo Client instance available to all child components
export default function App() {
  return (
    <ApolloProvider client={client}>
      <h1>My GraphQL App</h1>
      <CountriesList />
    </ApolloProvider>
  );
}
How it works: This React snippet demonstrates how to integrate with a GraphQL API 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. The `CountriesList` component uses the `useQuery` hook from `@apollo/client` to execute the query, providing `loading`, `error`, and `data` states. Finally, the root `App` component wraps its children with `ApolloProvider`, making the client accessible throughout the component tree. This setup streamlines data fetching, error handling, and caching for GraphQL APIs in React applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs