Explore // component/FootballDashboard.tsx 'use client' import { useState, useEffect } from… Save Share Download ▾ Report// component/FootballDashboard.tsx
'use client'
import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Button } from "@/components/ui/button"
import { RefreshCw, Play, LogIn, LogOut } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
import LiveScore from './LiveScore'
import LeagueSelector from './LeagueSelector'
import NewsArticles from './NewsArticles'
import PlayerSearch from './PlayerSearch'
import TeamHistory from './TeamHistory'
import FantasySports from './FantasySports'
import VideoContent from './VideoContent'
import AdminDashboard from './AdminDashboard'
const API_BASE_URL = 'http://localhost:5000 '
export default function HomePage() {
const [liveScores, setLiveScores] = useState<{ [key: string]: any[] } | null>(null)
const [articles, setArticles] = useState<any[]>([])
const [videos, setVideos] = useState<any[]>([])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [isAdmin, setIsAdmin] = useState(false)
useEffect(() => {
const token = localStorage.getItem('adminToken')
setIsAdmin(!!token)
code Copy code
const fetchData = async () => {
setIsLoading(true)
try {
const [scoresRes, articlesRes, videosRes] = await Promise.all([
fetch(`${API_BASE_URL}/api/scores`),
fetch(`${API_BASE_URL}/api/articles`),
fetch(`${API_BASE_URL}/api/videos/recent`)
])
const scoresData = await scoresRes.json()
const articlesData = await articlesRes.json()
const videosData = await videosRes.json()
setLiveScores(scoresData.data || {})
setArticles(articlesData.slice(0, 5)) // Limit to 5 articles
setVideos(videosData.response.slice(0, 3)) // Limit to 3 videos
setError(null)
} catch (error) {
console.error("Fetching error:", error)
setError("Failed to load data. Please try again later.")
} finally {
setIsLoading(false)
}
}
fetchData()
const intervalId = setInterval(fetchData, 60000) // Refresh every minute
return () => clearInterval(intervalId)
Show full message · 982 lines Assistant2024-11-14 16:20 UTC Copy response
Copy first prompt
Details
Provider openai
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Added to archive Nov 24, 2026
ID 01m86ekgwdfvgcp42nxe3hngtwSource & license Imported from WildChat-4.8M (source ). Imported records earn no Research Points.
Upstream record: dfe2174771b3113096262caebbe4ed71
allenai/WildChat-4.8M, revision c827c6df8fcf008219ffaffa4d1dd77491099367
License: ODC-BY-1.0
Dataset releases Not yet included in a published release.
const handleLogout = () => {
localStorage.removeItem('adminToken')
setIsAdmin(false)
}
const MatchRow = ({ match }: { match: any }) => (
{match.homeTeam.shortName}
{match.score.fullTime.home != null ? match.score.fullTime.home : '-'} -
{match.score.fullTime.away != null ? match.score.fullTime.away : '-'}
{match.status === 'FINISHED' ? 'FT' : match.status === 'IN_PLAY' ? "LIVE" : ""}
{match.awayTeam.shortName}
)
return (
FootballBuzz
{isAdmin ? (
Logout
) : (
Admin Login
)}
code Copy code
<Tabs defaultValue="home">
<TabsList className="mb-6">
<TabsTrigger value="home">Home</TabsTrigger>
<TabsTrigger value="liveScore">Live Score</TabsTrigger>
<TabsTrigger value="leagues">Leagues</TabsTrigger>
<TabsTrigger value="news">News</TabsTrigger>
<TabsTrigger value="players">Players</TabsTrigger>
<TabsTrigger value="teams">Teams</TabsTrigger>
<TabsTrigger value="fantasy">Fantasy</TabsTrigger>
<TabsTrigger value="videos">Videos</TabsTrigger>
{isAdmin && <TabsTrigger value="admin">Admin</TabsTrigger>}
</TabsList>
<TabsContent value="home">
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Live Scores Section */}
<div className="lg:col-span-2">
<Card className="mb-8">
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-2xl font-bold">Live Scores</CardTitle>
<Button variant="ghost" size="sm" onClick={() => window.location.reload()}>
<RefreshCw size={16} />
</Button>
</CardHeader>
<CardContent>
<ScrollArea className="h-[400px] pr-4">
{isLoading ? (
<p>Loading live scores...</p>
) : error ? (
<p className="text-red-500">{error}</p>
) : liveScores && Object.keys(liveScores).length > 0 ? (
Object.entries(liveScores).map(([league, matches]) => (
<div key={league} className="mb-4">
<h3 className="font-semibold text-lg mb-2">{league}</h3>
{Array.isArray(matches) ? (
matches.map((match: any) => (
<MatchRow key={match.id} match={match} />
))
) : (
<p className="text-red-500">Invalid data format for league: {league}</p>
)}
</div>
))
) : (
<p>No live scores available at the moment.</p>
)}
</ScrollArea>
</CardContent>
</Card>
{/* News Articles Section */}
<Card>
<CardHeader>
<CardTitle className="text-2xl font-bold">Latest News</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{articles.map(article => (
<Card key={article.id} className="overflow-hidden">
<Image src={article.headingImage} alt={article.title} width={300} height={200} className="w-full h-40 object-cover" />
<CardContent className="p-4">
<h3 className="font-semibold text-lg mb-2">{article.title}</h3>
<p className="text-sm text-gray-600">{article.content.substring(0, 100)}...</p>
</CardContent>
</Card>
))}
</div>
</CardContent>
</Card>
</div>
{/* Videos Section */}
<div>
<Card>
<CardHeader>
<CardTitle className="text-2xl font-bold">Featured Videos</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{videos.map(video => (
<div key={video.id} className="relative">
<Image src={video.thumbnail} alt={video.title} width={300} height={200} className="w-full rounded-lg" />
<div className="absolute inset-0 flex items-center justify-center">
<Play className="h-12 w-12 text-white bg-black bg-opacity-50 rounded-full p-3" />
</div>
<h4 className="mt-2 font-semibold">{video.title}</h4>
</div>
))}
</div>
</CardContent>
</Card>
</div>
</div>
</TabsContent>
<TabsContent value="liveScore">
<LiveScore />
</TabsContent>
<TabsContent value="leagues">
<LeagueSelector />
</TabsContent>
<TabsContent value="news">
<NewsArticles />
</TabsContent>
<TabsContent value="players">
<PlayerSearch />
</TabsContent>
<TabsContent value="teams">
<TeamHistory />
</TabsContent>
<TabsContent value="fantasy">
<FantasySports />
</TabsContent>
<TabsContent value="videos">
<VideoContent />
</TabsContent>
{isAdmin && (
<TabsContent value="admin">
<AdminDashboard />
</TabsContent>
)}
</Tabs>
</div>
)
}
This is football Dashboard
Other than error there is problem with images kinda of not seeing image that is uploaded and
Unhandled Runtime Error
TypeError: article.content.substring is not a function
Source
component\FootballDashboard.tsx (171:81) @ substring
169 |
170 | {article.title}
171 | {article.content.substring(0, 100)}...
| ^
172 |
173 |
174 | ))}
Call Stack
Show collapsed frames
Remove this error
const Article = require("../models/Article");
const { handleControllerError } = require("../utils/errorHandler");
// Function to handle uploading a new article
const addArticle = async (req, res) => {
try {
const { title, content, author } = req.body;
const headingImage = req.file ? /uploads/${req.file.filename} : null;
code Copy code
if (!title || !content || !author) {
return res.status(400).json({ message: "All fields are required." });
}
const newArticle = new Article({
title,
content,
author,
headingImage,
});
await newArticle.save();
res
.status(201)
.json({
message: "Article uploaded successfully.",
articleId: newArticle._id,
});
} catch (error) {
handleControllerError(error, res, "addArticle");
}
};
// Function to fetch all articles
const getArticles = async (req, res) => {
try {
const articles = await Article.find().sort({ createdAt: -1 });
res.json(articles);
} catch (error) {
handleControllerError(error, res, "getArticles");
}
};
// Function to fetch a single article by ID
const getArticleById = async (req, res) => {
try {
const { id } = req.params;
const article = await Article.findById(id);
code Copy code
if (!article) {
return res.status(404).json({ message: "Article not found." });
}
res.json(article);
} catch (error) {
handleControllerError(error, res, "getArticleById");
}
};
module.exports = {
getArticles,
addArticle,
getArticleById,
};
This is articleController.js
// controllers/adminController.js
const Article = require("../models/Article");
const News = require("../models/News");
const { handleControllerError } = require("../utils/errorHandler");
const fs = require("fs");
const path = require("path");
// Helper function to delete files
const deleteFile = (filePath) => {
fs.unlink(path.join(__dirname, "..", filePath), (err) => {
if (err) console.error(Failed to delete file ${filePath}:, err);
});
};
// --- Articles CRUD Operations ---
// Create a new article
const addArticle = async (req, res) => {
try {
const { title, content, author } = req.body;
const headingImage = req.file ? /uploads/${req.file.filename} : null;
code Copy code
if (!title || !content || !author) {
return res.status(400).json({ message: "All fields are required." });
}
const newArticle = new Article({
title,
content,
author,
headingImage,
createdBy: req.admin._id,
});
await newArticle.save();
res.status(201).json({
message: "Article created successfully.",
article: newArticle,
});
} catch (error) {
handleControllerError(error, res, "addArticle");
}
};
// Get all articles
const getAllArticles = async (req, res) => {
try {
const articles = await Article.find()
.populate("createdBy", "username")
.sort({ createdAt: -1 });
res.json(articles);
} catch (error) {
handleControllerError(error, res, "getAllArticles");
}
};
// Get a single article by ID
const getArticleById = async (req, res) => {
try {
const { id } = req.params;
const article = await Article.findById(id).populate(
"createdBy",
"username"
);
code Copy code
if (!article) {
return res.status(404).json({ message: "Article not found." });
}
res.json(article);
} catch (error) {
handleControllerError(error, res, "getArticleById");
}
};
// Update an existing article
const updateArticle = async (req, res) => {
try {
const { id } = req.params;
const { title, content, author } = req.body;
let headingImage;
code Copy code
const article = await Article.findById(id);
if (!article) {
return res.status(404).json({ message: "Article not found." });
}
if (req.file) {
// Delete the old image if it exists
if (article.headingImage) {
deleteFile(article.headingImage);
}
headingImage = `/uploads/${req.file.filename}`;
article.headingImage = headingImage;
}
// Update fields if provided
if (title) article.title = title;
if (content) article.content = content;
if (author) article.author = author;
await article.save();
res.json({ message: "Article updated successfully.", article });
} catch (error) {
handleControllerError(error, res, "updateArticle");
}
};
// Delete an article
const deleteArticle = async (req, res) => {
try {
const { id } = req.params;
code Copy code
const article = await Article.findByIdAndDelete(id);
if (!article) {
return res.status(404).json({ message: "Article not found." });
}
// Delete the heading image if it exists
if (article.headingImage) {
deleteFile(article.headingImage);
}
res.json({ message: "Article deleted successfully." });
} catch (error) {
handleControllerError(error, res, "deleteArticle");
}
};
const reviewArticle = async (req, res) => {
try {
const { id } = req.params;
const { review } = req.body;
code Copy code
const article = await Article.findById(id);
if (!article) {
return res.status(404).json({ message: "Article not found." });
}
// Assuming you have a reviews array in your Article model
article.reviews.push({
reviewer: req.admin._id,
review,
reviewedAt: new Date(),
});
await article.save();
res
.status(200)
.json({ message: "Article reviewed successfully.", article });
} catch (error) {
handleControllerError(error, res, "reviewArticle");
}
};
// --- News CRUD Operations ---
// Create a new news item
const addNews = async (req, res) => {
try {
const { title, content } = req.body;
const headingImage = req.files["headingImage"]
? /uploads/${req.files["headingImage"][0].filename}
: null;
const images = req.files["images"]
? req.files["images"].map((file) => /uploads/${file.filename})
: [];
code Copy code
if (!title || !content) {
return res
.status(400)
.json({ message: "Title and content are required." });
}
const newNews = new News({
title,
content,
headingImage,
images,
createdBy: req.admin._id,
});
await newNews.save();
res.status(201).json({
message: "News created successfully.",
news: newNews,
});
} catch (error) {
handleControllerError(error, res, "addNews");
}
};
// Get all news
const getAllNews = async (req, res) => {
try {
const newsList = await News.find()
.populate("createdBy", "username")
.sort({ createdAt: -1 });
res.json(newsList);
} catch (error) {
handleControllerError(error, res, "getAllNews");
}
};
// Get a single news item by ID
const getNewsById = async (req, res) => {
try {
const { id } = req.params;
const news = await News.findById(id).populate("createdBy", "username");
code Copy code
if (!news) {
return res.status(404).json({ message: "News not found." });
}
res.json(news);
} catch (error) {
handleControllerError(error, res, "getNewsById");
}
};
// Update an existing news item
const updateNews = async (req, res) => {
try {
const { id } = req.params;
const { title, content } = req.body;
let headingImage;
let images;
code Copy code
const news = await News.findById(id);
if (!news) {
return res.status(404).json({ message: "News not found." });
}
if (req.files["headingImage"]) {
// Delete the old heading image if it exists
if (news.headingImage) {
deleteFile(news.headingImage);
}
headingImage = `/uploads/${req.files["headingImage"][0].filename}`;
news.headingImage = headingImage;
}
if (req.files["images"] && req.files["images"].length > 0) {
// Optionally delete old carousel images
news.images.forEach((img) => deleteFile(img));
images = req.files["images"].map((file) => `/uploads/${file.filename}`);
news.images = images;
}
// Update fields if provided
if (title) news.title = title;
if (content) news.content = content;
await news.save();
res.json({ message: "News updated successfully.", news });
} catch (error) {
handleControllerError(error, res, "updateNews");
}
};
// Delete a news item
const deleteNews = async (req, res) => {
try {
const { id } = req.params;
code Copy code
const news = await News.findByIdAndDelete(id);
if (!news) {
return res.status(404).json({ message: "News not found." });
}
// Delete heading and carousel images if they exist
if (news.headingImage) {
deleteFile(news.headingImage);
}
news.images.forEach((img) => deleteFile(img));
res.json({ message: "News deleted successfully." });
} catch (error) {
handleControllerError(error, res, "deleteNews");
}
};
module.exports = {
// Articles
addArticle,
getAllArticles,
getArticleById,
updateArticle,
deleteArticle,
// News
addNews,
getAllNews,
getNewsById,
updateNews,
deleteNews,
reviewArticle,
};
// controllers/newsController.js
const { getCachedData } = require("../utils/cacheHelper");
const axiosInstance = require("../utils/axiosInstance");
// Centralized Error Handling for Controller
const handleControllerError = (error, res, functionName) => {
if (error.response) {
// API responded with a status code outside 2xx
console.error(
Error in ${functionName}: ${error.response.status} - ${JSON.stringify( error.response.data )}
);
res.status(error.response.status).json({
message: error.response.data.message || Error in ${functionName},
details: error.response.data,
});
} else if (error.request) {
// No response received from API
console.error(No response received in ${functionName}:, error.request);
res.status(503).json({
message: No response from Football API during ${functionName},
});
} else {
// Other errors
console.error(Error in ${functionName}:, error.message);
res
.status(500)
.json({ message: Internal server error in ${functionName} });
}
};
// Function to fetch top 10 players for a specific club
const getTopPlayersByClub = async (req, res) => {
const { club } = req.params; // e.g., 'barcelona', 'realmadrid'
const cacheKey = top_players_${club.toLowerCase()};
const fetchFn = async () => {
try {
const response = await axiosInstance.get(
/players/${encodeURIComponent(club.toLowerCase())}
);
// Assuming the API returns an array of player objects
const topPlayers = response.data.slice(0, 10); // Get top 10 players
return topPlayers;
} catch (error) {
throw error;
}
};
try {
const topPlayers = await getCachedData(cacheKey, fetchFn);
res.status(200).json({
club: club.charAt(0).toUpperCase() + club.slice(1),
topPlayers,
});
} catch (error) {
handleControllerError(error, res, getTopPlayersByClub ${club});
}
};
// Existing functions (getAllPlayers, getPlayersTransfers, etc.)
const getAllPlayers = async (req, res) => {
const cacheKey = "all_players";
const fetchFn = async () => {
const response = await axiosInstance.get("/players");
return response.data; // Assuming it's an array of players
};
try {
const players = await getCachedData(cacheKey, fetchFn);
res.status(200).json(players);
} catch (error) {
handleControllerError(error, res, "getAllPlayers");
}
};
const getPlayersTransfers = async (req, res) => {
const cacheKey = "players_transfers";
const fetchFn = async () => {
const response = await axiosInstance.get("/players/transfers");
return response.data; // Assuming it's an array of transfers
};
try {
const transfers = await getCachedData(cacheKey, fetchFn);
res.status(200).json(transfers);
} catch (error) {
handleControllerError(error, res, "getPlayersTransfers");
}
};
const getPlayersNews = async (req, res) => {
const cacheKey = "players_news";
const fetchFn = async () => {
const response = await axiosInstance.get("/players/news");
return response.data; // Assuming it's an array of news articles
};
try {
const news = await getCachedData(cacheKey, fetchFn);
res.status(200).json(news);
} catch (error) {
handleControllerError(error, res, "getPlayersNews");
}
};
const getBettingLaLiga = async (req, res) => {
const cacheKey = "betting_laliga";
const fetchFn = async () => {
const response = await axiosInstance.get("/betting/laliga");
return response.data; // Assuming it's betting information
};
try {
const laLigaData = await getCachedData(cacheKey, fetchFn);
res.status(200).json(laLigaData);
} catch (error) {
handleControllerError(error, res, "getBettingLaLiga");
}
};
const getBettingPremierLeague = async (req, res) => {
const cacheKey = "betting_premierleague";
const fetchFn = async () => {
const response = await axiosInstance.get("/betting/premuire-league"); // Fixed endpoint spelling
return response.data; // Assuming it's betting information
};
try {
const premierLeagueData = await getCachedData(cacheKey, fetchFn);
res.status(200).json(premierLeagueData);
} catch (error) {
handleControllerError(error, res, "getBettingPremierLeague");
}
};
// ... other functions as needed
module.exports = {
getAllPlayers,
getPlayersTransfers,
getPlayersNews,
getTopPlayersByClub,
getBettingLaLiga,
getBettingPremierLeague,
// ... other exports
};
// middlewares/upload.js
const multer = require("multer");
const path = require("path");
// Define storage for uploaded files
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/"); // Ensure this directory exists
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(null, uniqueSuffix + path.extname(file.originalname));
},
});
// File filter to accept only images and GIFs
const fileFilter = (req, file, cb) => {
const allowedTypes = /jpeg|jpg|png|gif/;
const extname = allowedTypes.test(
path.extname(file.originalname).toLowerCase()
);
const mimetype = allowedTypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
}
cb(new Error("Only images and GIFs are allowed"));
};
// Initialize multer
const upload = multer({
storage,
fileFilter,
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit, adjust as needed
});
// models/Article.js
const mongoose = require("mongoose");
const ContentBlockSchema = new mongoose.Schema({
type: {
type: String,
enum: [
"heading1",
"heading2",
"heading3",
"heading4",
"paragraph",
"image",
"carousel",
"gif",
"bulletList",
"numberList",
"link",
"blockCode",
],
required: true,
},
data: mongoose.Schema.Types.Mixed, // Flexible to store different data based on type
});
const ArticleSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
author: {
// Depending on your needs, this can reference the Admin
type: String,
required: true,
},
content: [ContentBlockSchema],
headingImage: {
type: String,
},
createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "Admin" },
status: {
// To track if article is published, under review, etc.
type: String,
enum: ["draft", "under_review", "published"],
default: "draft",
},
},
{ timestamps: true }
);
module.exports = mongoose.model("Article", ArticleSchema);
// routes/articleRoutes.js
const express = require("express");
const {
getAllArticles, // Corrected function name
addArticle,
getArticleById,
} = require("../controllers/adminController"); // Corrected path if using adminController.js
const router = express.Router();
const fs = require("fs");
const authenticateToken = require("../middlewares/authMiddleware");
const multer = require("multer");
const path = require("path");
// Configure Multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/"); // Temporary upload directory
},
filename: (req, file, cb) => {
const uniqueSuffix = ${Date.now()}-${Math.round(Math.random() * 1e9)};
cb(null, ${uniqueSuffix}-${file.originalname});
},
});
const upload = multer({
storage,
limits: { fileSize: 5 * 1024 * 1024 }, // Limit file size to 5MB
fileFilter: (req, file, cb) => {
const filetypes = /jpeg|jpg|png|gif/;
const mimetype = filetypes.test(file.mimetype);
const extname = filetypes.test(
path.extname(file.originalname).toLowerCase()
);
code Copy code
if (mimetype && extname) {
return cb(null, true);
}
cb(new Error("Only image files are allowed!"));
// Routes for user articles
router.get("/", getAllArticles); // Updated to match the controller function name
router.post(
"/add",
authenticateToken,
upload.single("headingImage"),
addArticle
); // POST /api/articles/add
router.get("/:id", getArticleById); // GET /api/articles/:id
module.exports = router;
// routes/admin.js
const express = require("express");
const router = express.Router();
const adminController = require("../controllers/adminController");
const { verifyToken } = require("../middlewares/auth");
const authorizeRoles = require("../middlewares/authorizeRoles");
const upload = require("../middlewares/upload");
// Protect all admin routes
router.use(verifyToken);
router.use(authorizeRoles("admin", "superuser"));
// --- Article Routes ---
// Publishers can create and update articles
router.post(
"/articles",
authorizeRoles("publisher", "admin", "superuser"),
upload.single("headingImage"),
adminController.addArticle
);
// Publishers and Admins can update articles
router.put(
"/articles/:id",
authorizeRoles("publisher", "admin", "superuser"),
upload.single("headingImage"),
adminController.updateArticle
);
// SuperUsers and Admins can delete any article
router.delete(
"/articles/:id",
authorizeRoles("admin", "superuser"),
adminController.deleteArticle
);
// Reviewers can review articles
router.post(
"/articles/:id/review",
authorizeRoles("reviewer", "admin", "superuser"),
adminController.reviewArticle
);
// Users can read articles
router.get(
"/articles",
authorizeRoles("user", "reviewer", "publisher", "admin", "superuser"),
adminController.getAllArticles
);
router.get(
"/articles/:id",
authorizeRoles("user", "reviewer", "publisher", "admin", "superuser"),
adminController.getArticleById
);
// Similar role-based access can be applied to news routes
Can you correct the error in the front end I'm using shadcn UI with the help of Nextjs in front end
To resolve the issues you're encountering with your Football Dashboard—specifically the runtime error and image display problems—let's address each problem step by step.
1. Fixing the Runtime Error: TypeError: article.content.substring is not a function
Root Cause:
The error arises because article.content is an array of content blocks rather than a string . The substring method is intended for string manipulation and cannot be used on arrays.
Solution:
You need to process the content array to extract plain text from it. Here's how you can achieve this:
a. Create a Helper Function to Extract Text:
First, define a function that iterates over the content array and concatenates the text from relevant blocks (like paragraphs and headings).
tsx Copy code
// helper.js or within your component file
const extractTextFromContent = (contentBlocks: any[]): string => {
return contentBlocks
.filter(block => ['paragraph', 'heading1', 'heading2', 'heading3', 'heading4'].includes(block.type))
.map(block => block.data.text || '')
.join(' ');
};
b. Update the Article Rendering Logic:
Use the helper function to extract text and then apply the substring method.
tsx Copy code
// component/FootballDashboard.tsx
import Image from 'next/image';
// ... other imports
export default function HomePage() {
// ... existing state and useEffect
// Helper function
const extractTextFromContent = (contentBlocks: any[]): string => {
return contentBlocks
.filter(block => ['paragraph', 'heading1', 'heading2', 'heading3', 'heading4'].includes(block.type))
.map(block => block.data.text || '')
.join(' ');
};
return (
<div className="container mx-auto px-4 py-8">
{/* ... existing code */}
{/* News Articles Section */}
<Card>
<CardHeader>
<CardTitle className="text-2xl font-bold">Latest News</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{articles.map(article => (
<Card key={article.id} className="overflow-hidden">
<Image
src={`${API_BASE_URL}${article.headingImage}`} // Ensure full URL
alt={article.title}
width={300}
height={200}
className="w-full h-40 object-cover"
onError={(e) => { (e.target as HTMLImageElement).src = '/fallback-image.jpg' }}
/>
<CardContent className="p-4">
<h3 className="font-semibold text-lg mb-2">{article.title}</h3>
<p className="text-sm text-gray-600">
{extractTextFromContent(article.content).substring(0, 100)}...
</p>
</CardContent>
</Card>
))}
</div>
</CardContent>
</Card>
{/* ... rest of the component */}
</div>
);
}
Explanation:
Helper Function: extractTextFromContent filters the content array for blocks that contain text (like paragraphs and headings) and concatenates their text content.
Rendering Articles: When mapping over articles, use the helper function to get a string of text from article.content and then apply substring(0, 100) to get the first 100 characters.
c. TypeScript Types (Optional but Recommended):
Define TypeScript interfaces to ensure type safety.
typescript Copy code
// types.ts or within your component file
interface ContentBlock {
type: string;
data: {
text?: string;
// ... other possible fields
};
}
interface Article {
id: string;
title: string;
author: string;
content: ContentBlock[];
headingImage: string;
// ... other fields
}
Update your state accordingly:
typescript Copy code
const [articles, setArticles] = useState<Article[]>([]);
2. Resolving Image Display Issues
Root Cause:
Images might not be displaying correctly due to incorrect paths or Next.js Image component restrictions. Since your images are served from http://localhost:5000/uploads, you need to ensure that Next.js can access these external images.
Solution:
a. Configure Next.js to Allow External Images:
Update your next.config.js to include the domain from which images are served.
javascript Copy code
// next.config.js
module.exports = {
images: {
domains: ['localhost'], // Add 'localhost' or your API's domain
},
};
Note: If your API is running on a different port (e.g., 5000), Next.js handles domains without considering ports, so localhost suffices.
b. Ensure Correct Image URLs:
When using the Image component, provide the full URL to the image.
tsx Copy code
<Image
src={`${API_BASE_URL}${article.headingImage}`} // e.g., "http://localhost:5000/uploads/image.jpg"
alt={article.title}
width={300}
height={200}
className="w-full h-40 object-cover"
/>
c. Handle Image Loading Errors:
Provide a fallback image in case the original image fails to load.
tsx Copy code
<Image
src={`${API_BASE_URL}${article.headingImage}`}
alt={article.title}
width={300}
height={200}
className="w-full h-40 object-cover"
onError={(e) => { (e.target as HTMLImageElement).src = '/fallback-image.jpg' }} // Ensure you have a fallback image in your public folder
/>
d. Verify Backend Image Serving:
Ensure that your backend server correctly serves images from the /uploads directory. You might need to set up static file serving in your backend if not already done.
For example, in Express.js:
javascript Copy code
// server.js or app.js
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from the "uploads" directory
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// ... rest of your server setup
3. Comprehensive Corrected Frontend Code
Here's the complete updated FootballDashboard.tsx with the fixes applied:
Key Changes:
Content Processing:
Introduced extractTextFromContent to process the content array and extract plain text.
Utilized this function when rendering the article's summary.
Image Handling:
Updated the src attribute of the Image component to include the full URL using API_BASE_URL.
Configured Next.js to allow images from localhost in next.config.js.
Added an onError handler to provide a fallback image if the original fails to load.
TypeScript Interfaces:
Defined ContentBlock and Article interfaces for better type safety and clarity.
Error Handling:
Ensured that if article.content is not an array, a default message is displayed.
3. Additional Recommendations
a. Verify Backend Serving of Images:
Ensure that your backend is correctly serving static files from the /uploads directory. In an Express.js setup, you can use:
javascript Copy code
const express = require('express');
const path = require('path');
const app = express();
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// ... other routes and middleware
b. Use Environment Variables:
Instead of hardcoding API_BASE_URL, use environment variables for better flexibility and security.
javascript Copy code
// .env.local
NEXT_PUBLIC_API_BASE_URL=http://localhost:5000
// component/FootballDashboard.tsx
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;
c. Optimize Image Loading:
Consider using Next.js's priority, placeholder, or lazy loading features for better performance.
tsx Copy code
<Image
src={`${API_BASE_URL}${article.headingImage}`}
alt={article.title}
width={300}
height={200}
className="w-full h-40 object-cover"
loading="lazy" // or "eager" based on your needs
placeholder="blur" // if you use blur placeholders
blurDataURL="/path-to-blur-image.jpg" // required if using "blur" placeholder
onError={(e) => { (e.target as HTMLImageElement).src = '/fallback-image.jpg' }}
/>
d. Enhance Error Messaging:
Provide more user-friendly error messages and possibly retry mechanisms for fetching data.
By implementing these solutions, you should be able to eliminate the runtime error related to article.content and ensure that images are displayed correctly in your Football Dashboard. Ensure that you test these changes thoroughly in your development environment before deploying them to production.
Show full message · 545 lines Copy first response
'use client'
import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Button } from "@/components/ui/button"
import { RefreshCw, Play, LogIn, LogOut } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
import LiveScore from './LiveScore'
import LeagueSelector from './LeagueSelector'
import NewsArticles from './NewsArticles'
import PlayerSearch from './PlayerSearch'
import TeamHistory from './TeamHistory'
import FantasySports from './FantasySports'
import VideoContent from './VideoContent'
import AdminDashboard from './AdminDashboard'
const API_BASE_URL = 'http://localhost:5000'
interface ContentBlock {
type: string;
data: {
text?: string;
// ... other possible fields
};
}
interface Article {
id: string;
title: string;
author: string;
content: ContentBlock[];
headingImage: string;
// ... other fields
}
export default function HomePage() {
const [liveScores, setLiveScores] = useState<{ [key: string]: any[] } | null>(null)
const [articles, setArticles] = useState<Article[]>([])
const [videos, setVideos] = useState<any[]>([])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [isAdmin, setIsAdmin] = useState(false)
useEffect(() => {
const token = localStorage.getItem('adminToken')
setIsAdmin(!!token)
const fetchData = async () => {
setIsLoading(true)
try {
const [scoresRes, articlesRes, videosRes] = await Promise.all([
fetch(`${API_BASE_URL}/api/scores`),
fetch(`${API_BASE_URL}/api/articles`),
fetch(`${API_BASE_URL}/api/videos/recent`)
])
const scoresData = await scoresRes.json()
const articlesData = await articlesRes.json()
const videosData = await videosRes.json()
setLiveScores(scoresData.data || {})
setArticles(articlesData.slice(0, 5)) // Limit to 5 articles
setVideos(videosData.response.slice(0, 3)) // Limit to 3 videos
setError(null)
} catch (error) {
console.error("Fetching error:", error)
setError("Failed to load data. Please try again later.")
} finally {
setIsLoading(false)
}
}
fetchData()
const intervalId = setInterval(fetchData, 60000) // Refresh every minute
return () => clearInterval(intervalId)
}, [])
const handleLogout = () => {
localStorage.removeItem('adminToken')
setIsAdmin(false)
}
const MatchRow = ({ match }: { match: any }) => (
<div className="flex items-center justify-between py-2 px-4 border-b last:border-b-0">
<div className="flex items-center space-x-2 w-5/12">
<Image src={match.homeTeam.crest} alt={match.homeTeam.name} width={24} height={24} className="rounded-full" />
<span className="font-medium text-sm">{match.homeTeam.shortName}</span>
</div>
<div className="flex flex-col items-center w-2/12">
<div className="text-sm font-bold">
{match.score.fullTime.home != null ? match.score.fullTime.home : '-'} -
{match.score.fullTime.away != null ? match.score.fullTime.away : '-'}
</div>
<div className="text-xs text-gray-500">
{match.status === 'FINISHED' ? 'FT' : match.status === 'IN_PLAY' ? "LIVE" : ""}
</div>
</div>
<div className="flex items-center justify-end space-x-2 w-5/12">
<span className="font-medium text-sm">{match.awayTeam.shortName}</span>
<Image src={match.awayTeam.crest} alt={match.awayTeam.name} width={24} height={24} className="rounded-full" />
</div>
</div>
)
// Helper function to extract text from content blocks
const extractTextFromContent = (contentBlocks: ContentBlock[]): string => {
return contentBlocks
.filter(block => ['paragraph', 'heading1', 'heading2', 'heading3', 'heading4'].includes(block.type))
.map(block => block.data.text || '')
.join(' ');
}
return (
<div className="container mx-auto px-4 py-8">
<div className="flex justify-between items-center mb-8">
<h1 className="text-4xl font-bold">FootballBuzz</h1>
{isAdmin ? (
<Button onClick={handleLogout} variant="outline">
<LogOut className="mr-2 h-4 w-4" /> Logout
</Button>
) : (
<Link href="/admin/login">
<Button variant="outline">
<LogIn className="mr-2 h-4 w-4" /> Admin Login
</Button>
</Link>
)}
</div>
<Tabs defaultValue="home">
<TabsList className="mb-6">
<TabsTrigger value="home">Home</TabsTrigger>
<TabsTrigger value="liveScore">Live Score</TabsTrigger>
<TabsTrigger value="leagues">Leagues</TabsTrigger>
<TabsTrigger value="news">News</TabsTrigger>
<TabsTrigger value="players">Players</TabsTrigger>
<TabsTrigger value="teams">Teams</TabsTrigger>
<TabsTrigger value="fantasy">Fantasy</TabsTrigger>
<TabsTrigger value="videos">Videos</TabsTrigger>
{isAdmin && <TabsTrigger value="admin">Admin</TabsTrigger>}
</TabsList>
<TabsContent value="home">
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Live Scores Section */}
<div className="lg:col-span-2">
<Card className="mb-8">
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-2xl font-bold">Live Scores</CardTitle>
<Button variant="ghost" size="sm" onClick={() => window.location.reload()}>
<RefreshCw size={16} />
</Button>
</CardHeader>
<CardContent>
<ScrollArea className="h-[400px] pr-4">
{isLoading ? (
<p>Loading live scores...</p>
) : error ? (
<p className="text-red-500">{error}</p>
) : liveScores && Object.keys(liveScores).length > 0 ? (
Object.entries(liveScores).map(([league, matches]) => (
<div key={league} className="mb-4">
<h3 className="font-semibold text-lg mb-2">{league}</h3>
{Array.isArray(matches) ? (
matches.map((match: any) => (
<MatchRow key={match.id} match={match} />
))
) : (
<p className="text-red-500">Invalid data format for league: {league}</p>
)}
</div>
))
) : (
<p>No live scores available at the moment.</p>
)}
</ScrollArea>
</CardContent>
</Card>
{/* News Articles Section */}
<Card>
<CardHeader>
<CardTitle className="text-2xl font-bold">Latest News</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{articles.map(article => (
<Card key={article.id} className="overflow-hidden">
<Image
src={`${API_BASE_URL}${article.headingImage}`} // Ensure full URL
alt={article.title}
width={300}
height={200}
className="w-full h-40 object-cover"
onError={(e) => { (e.target as HTMLImageElement).src = '/fallback-image.jpg' }}
/>
<CardContent className="p-4">
<h3 className="font-semibold text-lg mb-2">{article.title}</h3>
<p className="text-sm text-gray-600">
{extractTextFromContent(article.content).substring(0, 100)}...
</p>
</CardContent>
</Card>
))}
</div>
</CardContent>
</Card>
</div>
{/* Videos Section */}
<div>
<Card>
<CardHeader>
<CardTitle className="text-2xl font-bold">Featured Videos</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{videos.map(video => (
<div key={video.id} className="relative">
<Image src={`${API_BASE_URL}${video.thumbnail}`} alt={video.title} width={300} height={200} className="w-full rounded-lg" />
<div className="absolute inset-0 flex items-center justify-center">
<Play className="h-12 w-12 text-white bg-black bg-opacity-50 rounded-full p-3" />
</div>
<h4 className="mt-2 font-semibold">{video.title}</h4>
</div>
))}
</div>
</CardContent>
</Card>
</div>
</div>
</TabsContent>
{/* Other TabsContent... */}
<TabsContent value="liveScore">
<LiveScore />
</TabsContent>
<TabsContent value="leagues">
<LeagueSelector />
</TabsContent>
<TabsContent value="news">
<NewsArticles />
</TabsContent>
<TabsContent value="players">
<PlayerSearch />
</TabsContent>
<TabsContent value="teams">
<TeamHistory />
</TabsContent>
<TabsContent value="fantasy">
<FantasySports />
</TabsContent>
<TabsContent value="videos">
<VideoContent />
</TabsContent>
{isAdmin && (
<TabsContent value="admin">
<AdminDashboard />
</TabsContent>
)}
</Tabs>
</div>
)
}