Getting Started with Apollo Client and GraphQL in Next.js: A Step-by-Step Guide
Published: 2023-03-11 11:16:41

Here's a step-by-step guide on how to use Apollo Client library for client-side data collection from **GraphQL-based API** in Next.js framework:

**Step 1:** Install Required Dependencies
First, you need to install the required packages for the project by running the following command in your terminal:

```bash
npm install @apollo/client graphql
```
**Step 2:** Create an Apollo Client Instance
Create an Apollo Client instance in a separate file called apollo-client.js and export it to be used in the rest of the application.

```javascript

import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  uri: "https://countries.trevorblades.com",
  cache: new InMemoryCache(),
});

export default client;
```
Here, we've imported the `ApolloClient `and `InMemoryCache` classes from `@apollo/client`. The uri property specifies the endpoint of our **GraphQL** server. The cache property sets up an in-memory cache to store the results of our queries.

Step 3: Use the Apollo Provider Component in _app.js
To use the Apollo Client throughout our Next.js application, we need to wrap our root component with the ApolloProvider component. This component comes from the @apollo/client package.

Create a `_app.js` file in the `pages` directory, and use the `ApolloProvider` component to wrap the Component prop.

```javascript

import { ApolloProvider } from "@apollo/client";
import client from "../apollo-client";

function MyApp({ Component, pageProps }) {
  return (
    <ApolloProvider client={client}>
      <Component {...pageProps} />
    </ApolloProvider>
  );
}

export default MyApp;
```

**Step 4:** Write GraphQL Queries
Next, create a `.graphql` file to define your `GraphQL` queries. For this example, we'll create a file called `countries.graphql` in the queries directory.

```graphql

query Countries {
  countries {
    code
    name
    emoji
  }
}
```
This query requests the code, name, and emoji fields for all the countries in the API.

Step 5: Use `useQuery` Hook to Fetch Data
In your page component, import the `useQuery` hook from `@apollo/client` and use it to fetch the data. For this example, we'll create a file called index.js in the `pages` directory.

```javascript

import { useQuery } from "@apollo/client";
import { gql } from "@apollo/client";

const COUNTRIES_QUERY = gql`
  query Countries {
    countries {
      code
      name
      emoji
    }
  }
`;

export default function Home() {
  const { loading, error, data } = useQuery(COUNTRIES_QUERY);

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

  return (
    <div>
      <h1>Countries</h1>
      <ul>
        {data.countries.map((country) => (
          <li key={country.code}>
            {country.emoji} {country.name}
          </li>
        ))}
      </ul>
    </div>
  );
}
```
Here, we've imported the `useQuery` hook and the `gql` function from `@apollo/client`. The `COUNTRIES_QUERY` constant contains our GraphQL query defined in the `.graphql` file.

We're using the `useQuery` hook to fetch the data and store it in the data variable. The loading and error variables indicate the state of the query.