Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'map')…
- User
Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'map')
Source component\NewsArticles.tsx (73:23) @ map
71 | 72 |
73 | {articles.map((article, index) => ( | ^ 74 | <motion.div 75 | key={index} 76 | className="relative cursor-pointer rounded-lg overflow-hidden shadow-md" Call Stack
This is the error
// /app/components/NewsArticles.tsx
'use client'
import { useState, useEffect } from 'react' import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Skeleton } from "@/components/ui/skeleton" import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert" import { AlertCircle } from 'lucide-react' import Image from 'next/image' import { motion } from 'framer-motion' // For animations // import NewsModal from './NewsModal' // We'll create this next
interface Article { headLine: string url: string source: string }
interface ArticlesResponse { club: string topPlayers: Article[] }
export default function NewsArticles() { const [articles, setArticles] = useState<Article[]>([]) const [isLoading, setIsLoading] = useState(true) const [error, setError] = useState<string | null>(null) const [selectedArticle, setSelectedArticle] = useState<Article | null>(null)
useEffect(() => { const fetchArticles = async () => { try { const response = await fetch('http://localhost:5000/api/news/players') // Adjust the endpoint as needed if (!response.ok) { throw new Error('Failed to fetch news') } const data: ArticlesResponse = await response.json() setArticles(data.topPlayers) } catch (error) { console.error('Error fetching news:', error) setError('Failed to load news. Please try again later.') } finally { setIsLoading(false) } }
codefetchArticles()}, [])
if (isLoading) { return }
if (error) { return ( Error {error} ) }
return ( <> Latest News {articles.map((article, index) => ( <motion.div key={index} className="relative cursor-pointer rounded-lg overflow-hidden shadow-md" whileHover={{ scale: 1.02 }} onClick={() => setSelectedArticle(article)} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.5 }} > {/* Use a public placeholder image URL */} <Image src="https://via.placeholder.com/400x200?text=News+Image" // Placeholder image URL alt={article.headLine} width={400} height={200} className="w-full h-48 object-cover rounded-t-lg" placeholder="blur" blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAIAAACt...==" // A tiny base64-encoded image or omit if not needed onError={(e: any) => { e.target.onerror = null e.target.src = '' }} /> {article.headLine} Source: {article.source} </motion.div> ))}
- Assistant