Now that you have conceptually grasped GraphQL, let's actually use it in Next.js and see how it differs from the previously used Flux-based state management library. 🙂
Obviously, it is not necessary to use a library to call a GraphQL API. It is possible to simply call the fetch function alone, but using the library provides various functions and has advantages in various aspects such as development experience, so we will go ahead and install the library right away.
Among them, we will use the most used apollo client.
First, build the next environment using create-next-app and install the apollo and graphql packages.
yarn create next-app [Project Name]
cd [Project Name]
yarn add @apollo/client graphql
Now, if you have installed the desired package and type yarn dev
, the script specified in package.json is executed, and you can see that next.js is operating normally by node.js.
Let's write code that creates an apollo client instance to use the library.
// ./apollo-client.js
import { ApolloClient, InMemoryCache } from "@apollo/client";
const client = new ApolloClient({
uri: "<https://countries.trevorblades.com>",
cache: new InMemoryCache(),
});
export default client;
Enter the URL
of the gql server in uri and put an InMemoryCache
instance in cache
, which is used when caching data retrieved from the client.
Now, in order to run a query, we need to know what kind of data can be retrieved from the URL we have listed. At this time, Apollo Explorer
is used.
If you use Apollo Explorer, you can see what kind of data can be retrieved through the corresponding url like the API specification of the Rest API. First of all, if you create an account through the link and enter https://countries.trevorblades.com, the endpoint we entered, the following screen will appear.
You can check the schema here and run queries easily. (Think of it as a tool similar to the REST API's Postman.)
If you go to the Schema page, the data that can be imported is specified. Of these, we will bring and use the code
name
emoji
from Country.