Next.js is a React framework that allows programmers to create fast, static websites. It enables us to create hybrid apps with both server-rendered and statically created pages. There are also built-in integrations such as ESLint and TypeScript. Its growing popularity has made it widely been used in Web Application Development. In ThoughtLabs Belgium we are also using this framework for one of the client and we are in love with it and we really like recommending this Next.js framework to our clients.
What is GraphQL?
GraphQL is an API query language introduced by Facebook in 2012 that allows us to consume an API in a different way than the usual REST API. It’s made to make APIs more adaptable and quick. Instead of sending a GET call, we gather data with GraphQL. The GraphQL endpoint accepts a ‘query,’ which contains the data you wish to grab.
country {
"name": "Belgium",
"capital": "Brussels",
"currency": "EUR",
"population": "200000"
}
you can submit a request for only the name and currency.
What is Apollo GraphQL and how does it work?
Apollo GraphQL is a GraphQL implementation that allows you to declare your queries within the UI components that require them, and then have those components automatically updated when query results arrive or change. The useQuery Hook encapsulates any other functionality for getting data, tracking loading and error conditions, and changing your UI when using Apollo Client. This encapsulation makes it simple to integrate query results into your components.
Getting Started
We’ll make a Next.js web application that displays a list of countries and their data in this tutorial. We have a few choices for obtaining data in Next.js, but we’ll select the static generation approach (SSG). The getStaticProps method in Next.js allows us to collect data at various stages of the lifecycle, allowing us to create a totally static app that serves data that has already been displayed to the page to the browser.
In this tutorial, we’ll use the GraphQL API to construct a Next.js web application that displays a list of countries and their data.
For the app, we’ll install the necessary packages.
npx create-next-app country-list-with-graphql
npm install graphql
npm install @apollo/client
Start your development server when the packages have been installed.
cd country-list-with-graphql
npm run dev
Adding Apollo client to Next.js web application
Clean up the code in your ‘pages/index.js’ directory, which should now look like this.
export default function Home() {
return(
<div></div>
)
}
Then import the apollo client that was previously installed and define a new function beneath our component.
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";
export default function Home() {
return <div></div>;
}
export async function getStaticProps() {}
We’ll get props to utilise in our component with the getStaticProps method. We’re now ready to use the GraphQl API to get data.
Here, we’ll utilise the Apollo Client to interact with the Countries GraphQL server. We’ll use the Next.js getStaticProps method to make our API request, which will allow us to dynamically construct props for our page.
Appolo may use InMemoryCache to save the results of GraphQl queries in a cache. For passing queries to Apollo Client, gql is the recommended method. Now we must create a new Apollo Client instance within getStaticProps as follows:
const client = new ApolloClient({
uri: "https://countries.trevorblades.com",
cache: new InMemoryCache(),
});
Then we can make a query
const { data } = await client.query({
query: gql`
query {
countries {
name
native
capital
currency
continent {
name
}
phone
languages {
name
}
}
}
`,
});
This produces a new GraphQl query within the gql tag, then uses client.query to make a new query request, and lastly, data is destructured from the results, which is where the information we require is saved.
We describe what we want from the API within the query, which is countries, which returns a list of all countries, and then we can define what we want from each country.
We must now return data from getStaticProps and console log it in our component in order to view what the data looks like in the console. This is because getStaticProps runs during the build process.
return {
props: {
data: data.countries,
},
};
To view what our data looks like, we can now console log the results in the component.
export default function Home(results) {
console.log(results)
return <div></div>;
}
This is how your console should appear
Adding the countries data
We have the data for the countries, which we obtained by using the Apollo Client to make a request to the countries’ GraphQL server. Create a directory called components and a file called countries.js at the root of our project, and set it up like this:
export default function Countries () {
return(
<div></div>
)
}
Return to the pages/index.js directory, import the Countries component, and render it with the results passed in as props.
<section>
<div>
<div>
<h1>Countries Data</h1>
</div>
<Countries countries={results} />
</div>
</section>
Return to the components/countries.js directory and add the code below.
export default function Countries({ countries }) {
return (
<section>
<div>
{countries.data.map((country, index) => (
<div key={index}>
<h3>{country.name}</h3>
<h5>
Capital: <span> {country.capital} </span>{" "}
</h5>
<p>
Continent: <span> {country.continent.name} </span>{" "}
</p>
<p>
Languages:
{country.languages.map((item, index) => (
<span key={index}>{item.name},</span>
))}
</p>
<p>
Currency:
<span>{country.currency}</span>
</p>
<p>
Phone:
<span>+{country.phone}</span>
</p>
</div>
))}
</div>
</section>
);
}
The countries list is now complete, and we can view all of the data we requested. Additional data can be added to the GraphQl query. Check out the documentation, then head to the playground to put some questions to the test.