"use client"; import { useState, useEffect } from "react"; import axios from "axios"; // 1. Define the TypeScript interface for a News Article item interface Article { id: number; title: string; body: string; } export default function NewsPage() { // 2. Setup state for data, loading, and error handling const [articles, setArticles] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // 3. Fetch data inside useEffect useEffect(() => { // Create an AbortController to cleanup on component unmount const controller = new AbortController(); const fetchNews = async () => { try { setLoading(true); setError(null); // Fetch top 6 mock news articles using Axios const response = await axios.get( "https://jsonplaceholderrr.typicode.com/posts?_limit=6", { signal: controller.signal } ); console.log(response.data); setArticles(response.data); } catch (err: unknown) { console.log("error", err); // Ignore errors caused by unmounting (aborted requests) if (axios.isCancel(err)) return; if (axios.isAxiosError(err)) { setError(err.message || "Failed to fetch news articles."); } else { setError("An unexpected error occurred."); } } finally { setLoading(false); } }; fetchNews(); // Cleanup function runs if the component unmounts return () => { controller.abort(); }; }, []); // Empty dependency array = runs ONCE when component mounts // 4. Render Loading State (DaisyUI Loading Spinner) if (loading) { return (

Fetching latest news...

); } // 5. Render Error State (DaisyUI Alert) if (error) { return (
{error}
); } // 6. Render Data on JSX (DaisyUI Card Grid) return (
{/* Header */}

Trending Headlines

Fetched via Axios + useEffect

{/* Article Grid */}
{articles.map((article) => (
News #{article.id}

{article.title}

{article.body}

))}
); }