How to setup Apollo Client to perform GraphQL queries with NextJS
In the previous article Setting up GraphQL API with MongoDB and Apollo Server for a NextJS app we’ve created a GraphQL API with Apollo Server setup and connection to the MongoDB. We worked mainly on the server-side of the application.
It’s recommended to read and follow along the first part if you haven’t.
In this article, we’re moving to the client-side of the application and we’ll learn how to consume an API that we’ve created in the first part. Meaning, performing queries from our NextJS application to the GraphQL API.
To perform queries to our GraphQL API from the client-side (and not only from the GraphQL Playground), we’ll need to set up Apollo Client.
Using a custom implementation of the
withApollo() high-order component we are going to wrap index file with it and make queries to the API.
yarn add apollo-client @apollo/react-hooks @apollo/react-ssr apollo-cache-inmemory apollo-link-http apollo-link-schema graphql-tag
Setting up an Apollo Client
At the project root let’s create a folder called
apollo/ with a
client.js file inside.
Sharing schema between Apollo Client and Apollo Server
Our GraphQL schema is located now under the
pages/api/graphql.js alongside with our Apollo Server setup.
Before we had all the setup in on file on the server, like so:
However, we need to access schema on the client-side as well so let’s move
schema setup to the
apollo folder on the client and just import it on the server.
apollo/ folder let's create
schema.js files and move respective parts in there so you would have a file structure like this:
After moving files to the client our Apollo Server setup looks nice and clean:
After the refactoring our API still works as expected:
Create Users component and perform queries to the GraphQL API
components/Users.js component which will display a list of users:
Wrap Index file
In order for GraphQL Queries to work, we need to wrap our Index page
Let’s refactor our Index page to display the Users component and import
That’s it! We can perform queries to our GraphQL API with Apollo Client and fetch data from the MongoDB.
Originally published at https://grischuk.de on June 10, 2020.