API call in Next.js

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.

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.

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

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

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *