Blog>
Snippets

Integrating GraphQL Data Fetching

Demonstrate the integration of GraphQL queries in a Next.js app using Apollo Client or a similar GraphQL client for fetching data.
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client';
import { MyApp } from './MyApp';

// Initialize ApolloClient
const client = new ApolloClient({
  uri: 'https://your-graphql-endpoint.com/graphql',
  cache: new InMemoryCache(),
});

// Wrap your Next.js app with ApolloProvider
const App = () => (
  <ApolloProvider client={client}>
    <MyApp />
  </ApolloProvider>
);

export default App;
This code snippet initializes ApolloClient with a GraphQL endpoint and wraps the Next.js application with ApolloProvider, allowing any component in the app to have access to the GraphQL API.
import { gql, useQuery } from '@apollo/client';

// Define a GraphQL query
const GET_DATA = gql`
  query GetData($id: ID!) {
    item(id: $id) {
      id
      name
      description
    }
  }
`;

// Create a React component that uses the useQuery hook to fetch data
const DataFetcher = ({ itemId }) => {
  const { loading, error, data } = useQuery(GET_DATA, { variables: { id: itemId } });

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

  return (
    <div>
      <h2>{data.item.name}</h2>
      <p>{data.item.description}</p>
    </div>
  );
};

export default DataFetcher;
Here we have a React component that performs a GraphQL query using the useQuery hook from Apollo Client. The component fetches data for a specific item based on the provided itemId prop and handles loading and error states.
/* styles.css */

/* Simple CSS for the data fetcher component */
p {
  color: #666;
}

div {
  padding: 20px;
  border: 1px solid #ddd;
  margin-top: 10px;
}

h2 {
  color: #333;
}
A simple CSS file to style the DataFetcher component. It applies basic styling to paragraphs, div containers, and h2 elements to improve the visual presentation of the GraphQL data.