How to Fetch From Nextjs Api and Render in Component ?

How to Fetch From Nextjs Api and Render in Component ?

  • Create a Next.js API route (/api/data) that hosts a JSON response.

  • Create a UI component (DataList) that fetches and renders the data.

  • Use the UI component in a page (/pages/index.js) to display the data.

https://www.youtube.com/watch?v=ksWpvLIFVLw

Create Api Route

import { NextResponse } from "next/server";

export async function GET() {
  const data = [
    { id: 1, name: "Item 1", description: "This is item 1" },
    { id: 2, name: "Item 2", description: "This is item 2" },
    { id: 3, name: "Item 3", description: "This is item 3" },
  ];

  return NextResponse.json(data);
}

Create Ui Component

"use client";

import { useEffect, useState } from "react";

export default function DataList() {
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch("/api/data")
      .then((res) => res.json())
      .then((data) => setItems(data));
  }, []);

  return (
    <div>
      <h2>Data List</h2>
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            <strong>{item.name}</strong>: {item.description}
          </li>
        ))}
      </ul>
    </div>
  );
}

This will render the API data dynamically in your Next.js app.