Ads

NextJs - Create NextJS API and consume in ReactJS Components


Hello All,

Welcome to NextJS article, in this article we will learn about api creation using NextJs and consume same in ReactJS Components.


Lets begining the Creation of application.

1. Create folder called simple-api-and-ui


2. Go to folder simple-api-and-ui
3. Shift Right click on folder and open command prompt here.
4. Run the below command to create the next js application

    create-next-app .



5. Please select the below options and enter



Great! finally application created successfully 😀

 


6. Open the application in VS Code.



7. Just run the application, no need to to anything

    Go to command prompt and the below command

    npm run dev

 


 

Next go to any browser(Edge/Chrome/Firefox/Safari) and browse :  http://localhost:3000

You will see the below page



Application is running as expected

Next step is to create the api

8. Under app folder create folder called api and create foldeuser r inside api folder.



Next lets create file called route.js

const userData = [
  {
    id: "123",
    fullname: "test user",
    email: "testuser@test.com",
    statue: "active",
  },
  {
    id: "124",
    fullname: "test user1",
    email: "testuser1@test.com",
    statue: "active",
  },
];

export const GET = async (request) => {
  return new Response(JSON.stringify(userData), { status: 200 });
};

We have created dummy data(userData) and sending that data as response

Lets run the application and browse URL : localhost:3000/api/user

and output will be

Creating UI Component to consume the API Endpoint.


9. Create user folder inside app folder



inside user folder create page.js file, and lets add the below code in it

"use client";
import React, { useEffect, useState } from "react";

const UserList = () => {
  const [user, setUser] = useState([]);

  const fetchUser = async () => {
    const response = await fetch("/api/user");
    const userList = await response.json();
    setUser(userList);
  };

  useEffect(() => {
    fetchUser();
  }, []);

  return (
    <div>
      <table>
        <thead>
          <tr>
            <td>EmpId</td>
            <td>FullName</td>
            <td>EmailId</td>
            <td>Status</td>
          </tr>
        </thead>
        <tbody>
          {!user ? (
            <tr>No User Data Found</tr>
          ) : (
            <>
              {user.map((item, index) => (
                <tr key={index}>
                  <td>{item.id}</td>
                  <td>{item.fullname}</td>
                  <td>{item.email}</td>
                  <td>{item.status}</td>
                </tr>
              ))}
            </>
          )}
        </tbody>
      </table>
    </div>
  );
};

export default UserList;


Lets browse the URL, http://localhost:3000/user

We will see the below output


Boom!!!! application is working as expected

In our UI Code, we have created the const variable user to hold the user data which is fetched from API.

 const [user, setUser] = useState([]);

Calling api and storing the userList to const variable

  const fetchUser = async () => {
    const response = await fetch("/api/user");
    const userList = await response.json();
    setUser(userList);
  };

Thats it for this article, I hope you enjoyed this article

Lets see you in next article.

Until than take care bye 😀

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !