Blog>
Snippets

Using Graphql with Apollo Client

Illustrate the integration of Apollo Client with Next.js 14 for querying a GraphQL API, including setup and executing a query in a component.
import { ApolloClient, InMemoryCache, gql, useQuery } from '@apollo/client';

// Initializing Apollo Client
const client = new ApolloClient({
  uri: 'your-graphql-api-endpoint', // Replace with your GraphQL API endpoint
  cache: new InMemoryCache(),
});

export default client;
This code initializes Apollo Client with an in-memory cache and sets the URI to the GraphQL API endpoint.
import { ApolloProvider } from '@apollo/client';
import client from '../path/to/your/apollo-client'; // Adjust the path to where your Apollo client is exported
import React from 'react';
import { NextPage } from 'next';

const MyApp: NextPage = ({ Component, pageProps }) => (
  <ApolloProvider client={client}>
    <Component {...pageProps} />
  </ApolloProvider>
);

export default MyApp;
This snippet wraps the Next.js application with the ApolloProvider component, providing the Apollo Client instance to the rest of the app.
import { gql, useQuery } from '@apollo/client';

const GET_DATA = gql`
  query GetData {
    data { // adjust this to your actual query and fields
      id
      value
    }
  }
`;

const YourComponent = () => {
  const { loading, error, data } = useQuery(GET_DATA);

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

  return (
    <div>
      {data.data.map(item => (
        <div key={item.id}>{item.value}</div> // Render your query data here
      ))}
    </div>
  );
};

export default YourComponent;
This component defines a GraphQL query using the gql function and then executes the query within the component using the useQuery hook from Apollo Client. It handles the loading and error states and renders the fetched data.