How To Call Web API In Next JS Application Using Axios

Introduction

Here we get the Data from API using Axios in Next JS and show that data in a table.

Here is the link to learn about Axios.

Preconditions

  • Javascript
  • Basic knowledge of Next JS
  • Node.js
  • V.S. Code,Visual Studio

We cover the below things,

  • Create Next application
  • Installation of PrimeFlex in Next JS

Step 1

Run the below command to create the Next JS application.

npx create-next-app primeflexappnextapicall
cd primeflexappnextapicall
npm run dev

Step 2

Run the below command for installing Axios, and react-bootstrap.

npm i axios
npm i react-bootstrap

Create the files according to the below image

How to call Web API in Next Js application using axios.

Step 3

Add the below code in the index.js

import Head from 'next/head'
import Image from 'next/image'
import { Inter } from 'next/font/google'
import styles from '@/styles/Home.module.css'
import MyApiCallInNextPage from './MyApiCallInNextPage'

const inter = Inter({ subsets: ['latin'] })

export default function Home() {
  return (
    <>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
        <link rel="stylesheet" href="https://unpkg.com/primeflex@^3/primeflex.css" />
        <link rel="stylesheet" href="https://unpkg.com/primeflex/themes/saga-blue.css" />
        <link rel="stylesheet" href="https://unpkg.com/primeflex/themes/arya-blue.css" />
        <link rel="stylesheet" href="https://unpkg.com/primeflex/themes/vela-blue.css" />
        <script src="https://cdn.jsdelivr.net/npm/react/umd/react.production.min.js" crossorigin></script>
        <script src="https://cdn.jsdelivr.net/npm/react-dom/umd/react-dom.production.min.js" crossorigin></script>
        <script src="https://cdn.jsdelivr.net/npm/react-bootstrap@next/dist/react-bootstrap.min.js" crossorigin></script>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous" />
      </Head>
      <main className={styles.main}>
        <div className={styles.grid}>
          <MyApiCallInNextPage />
        </div>
      </main>undefined
    </>
  )
}

Step 4

Add the below code in MyApiCallInNextPage.js

import Image from 'next/image'
import styles from '@/styles/Home.module.css';
import Link from 'next/link';
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react';
import axios from 'axios';
import Table from 'react-bootstrap/Table';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Col, Row } from 'react-bootstrap';

const MyApiCallInNextPage = () => {
        const router = useRouter();
        const [Datas, setDatas] = useState([]);
        useEffect(() => {
            axios.get('https://jsonplaceholder.typicode.com/users').then(function(response) {
                setDatas(response.data);
                console.log(Datas)
            }).catch(function(error) {
                console.log(error);
            });
        }, [Datas])
        console.log('Data:', Datas);
return (
<>
  <main className={styles.main} style={{padding: '0px'}}>
    <div className={styles.grid}>
      <h1>API Data</h1>
      <Row>
        <Col lg={12}>
        <Table striped bordered hover variant="dark">
          <thead>
            <tr>
              <th>Name</th>
              <th>User Name</th>
              <th>Email Id</th>
              <th>City</th>
              <th>Zip Code</th>
              <th>Suite</th>
            </tr>
          </thead>
          <tbody> {Datas.filter(a => a.id < 6).map((datas, index)=>
              <tr key={index}>
                <td>{datas.name}</td>
                <td>{datas.username}</td>
                <td>{datas.email}</td>
                <td>{datas.address.city}</td>
                <td>{datas.address.zipcode}</td>
                <td>{datas.address.suite}</td>
              </tr> )} </tbody>
        </Table>
        </Col>
      </Row>
    </div>
  </main>undefined
 </>
 )
}
export default MyApiCallInNextPage

Step 5

Create globals.css and Home.module.css. You can get the CSS code from the attached code.

Step 6

Add the following code in package.json

{
  "name": "primeflexappnextapicall",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "axios": "^1.3.4",
    "bootstrap": "^5.2.3",
    "next": "13.2.4",
    "react": "18.2.0",
    "react-bootstrap": "^2.7.2",
    "react-dom": "18.2.0"
  }
}

Step 7

Run the following commands

npm i
npm run dev

How to call Web API in Next Js application using axios.

Summary

In this article, we learned how to create a Next JS application and install Prime Flex Axios. We also learned here how to fetch data from Web API.