Clue Mediator

API call in Next.js

📅March 3, 2020

Today we’ll show you how to make API call in Next.js and display records in grid. As we already show you how to call API in ReactJS. So in this article, we will place API calls and display records in the table form.

API call in Next.js, Learn & Example - Fetching Data for Pages | Next.js, NextJs Data fetching - Combine Server Side and Client Side, example of next js API request calls, API call using getInitialProps, How to call API in next.js, Next js tutorial fetch api data.

Checkout more articles on Next.js/ReactJS

Let’s implement the example where we will call the API using `axios` package and display the fetched records in the table.

Steps to place API call in Next.js

  1. Setup Next.js application
  2. Install axios
  3. Implement API call
  4. Output

1. Setup Next.js application

In this example, we'll place API call and display records in simple design. Our goal is to show you the functionality. So let's start with the setup of the Next.js application. If you don't know how to do it then please follow the link below for your reference.

How to setup a project in Next.js

2. Install axios

In this example we will use the `axios` npm package to call the API. Use the command below to install `axios` in the project.

npm i axios

3. Implement API call

Now we’ll use the `getInitialProps` method to call the API. `getInitialProps` method will be called at both server and client side. This method is also supported as an async function. Any value returned from this method that we can get through the props in the components.

Here we created the async function to call API using the `axios` npm package and we display the API response in the form of the table.

index.js

import axios from "axios";

const Index = ({ userList }) => <div style={{ margin: 20 }}>
  <h3><a href="https://www.cluemediator.com/" target="_blank">Clue Mediator</a></h3>
  <table border="1">
    <thead>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Avatar</th>
    </thead>
    <tbody>
      {userList.data.map((x, i) => <tr key={i}>
        <td>{x.first_name}</td>
        <td>{x.last_name}</td>
        <td>{x.email}</td>
        <td><img src={x.avatar} width="50" height="50" /></td>
      </tr>)}
    </tbody>
  </table>
</div>

Index.getInitialProps = async () => {
  const { data } = await axios.get('https://reqres.in/api/users');
  return { userList: data };
}

export default Index;

3. Output

Run the project and check the output on the `http://localhost:3000` link.

Output - API call in Next.js - Clue Mediator

Output - API call in Next.js - Clue Mediator

That's it for today.
Thank you for reading. Happy Coding!

Demo & Source Code

Github Repository