Blog>
Snippets

GraphQL Data Fetching with Apollo Client

Set up Apollo Client in a Next.js application to fetch data from a GraphQL API using the useQuery hook.
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
import { ApolloProvider } from '@apollo/client/react';

// Initialize ApolloClient
const client = new ApolloClient({
  uri: 'YOUR_GRAPHQL_API_ENDPOINT', // Replace with your GraphQL endpoint
  cache: new InMemoryCache()
});
This code initializes the Apollo Client with the provided GraphQL API endpoint and sets up an in-memory cache for caching query results.
import { useQuery } from '@apollo/client';

// Define your GraphQL query
const GET_DATA_QUERY = gql`
  query GetData {
    exampleField {
      id
      name
      // Add more fields as needed
    }
  }
`;

// Data fetching React component
const MyComponent = () => {
  const { loading, error, data } = useQuery(GET_DATA_QUERY);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  // Render fetched data
  return (
    <div>
      {data.exampleField.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
};
This code defines a GraphQL query using the gql template literal and fetches data inside a React component using the useQuery hook. It handles loading and error states and renders the fetched data.
import React from 'react';
import { ApolloProvider } from '@apollo/client/react';
import { client } from './apolloClient';

// Next.js application with Apollo Provider
const MyApp = ({ Component, pageProps }) => (
  <ApolloProvider client={client}>
    <Component {...pageProps} />
  </ApolloProvider>
);

export default MyApp;
This code snippet wraps the Next.js application with the ApolloProvider and passes the Apollo Client instance to it, making it available to any component in the application.