Ready to combine these tools? Let’s build a Next.js app that fetches data from a GraphQL API.
Step 1: Set Up Your Next.js Project
Run the following command to create a new Next.js app:
npx create-next-app my-next-graphql-app
cd my-next-graphql-app
Step 2: Install Apollo Client
Apollo Client is the go-to library for working with GraphQL in JavaScript. Install it with:
npm install @apollo/client graphql
Step 3: Set Up Apollo Provider
The Apollo Provider makes GraphQL data accessible throughout your app. Add it to the pages/_app.js file:
// pages/_app.js
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client';
import '../styles/globals.css';
const client = new ApolloClient({
uri: 'YOUR_GRAPHQL_API_ENDPOINT', // Replace with your GraphQL endpoint
cache: new InMemoryCache(),
});
function MyApp({ Component, pageProps }) {
return (
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
);
}
export default MyApp;
Step 4: Fetch Data with GraphQL
Create a page that fetches data from your GraphQL API.
// pages/index.js
import { useQuery, gql } from '@apollo/client';
const GET_DATA = gql`
query {
data {
id
value
}
}
`;
const HomePage = () => {
const { loading, error, data } = useQuery(GET_DATA);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h1>Data from GraphQL</h1>
<ul>
{data.data.map((item) => (
<li key={item.id}>{item.value}</li>
))}
</ul>
</div>
);
};
export default HomePage;
Step 5: Run Your Application
Start your app:
npm run dev
Visit http://localhost:3000 in your browser, and you’ll see your app fetching data from the GraphQL API.