'use client' import React, { useState, useEffect } from 'react'; import { Card,…
- User
'use client'
import React, { useState, useEffect } from 'react'; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Skeleton } from "@/components/ui/skeleton"; import { motion, AnimatePresence } from "framer-motion"; import { RefreshCw, ChevronDown, ChevronUp } from 'lucide-react';
const API_BASE_URL = 'http://localhost:5000'; const SCORE_REFRESH_DELAY = 60000; // 1 minute for scores const TEAM_REFRESH_DELAY = 300000; // 5 minutes for team names const LEAGUE_REFRESH_DELAY = 3600000; // 1 hour for league names
interface Team { id: number; name: string; shortName: string; tla: string; crest: string; }
interface Score { winner: string | null; duration: string; fullTime: { home: number | null; away: number | null; }; halfTime: { home: number | null; away: number | null; }; }
interface Match { id: number; utcDate: string; status: string; homeTeam: Team; awayTeam: Team; score: Score; }
interface LiveScores { [key: string]: Match[]; }
const leagueColors: { [key: string]: string } = { 'UEFA Champions League': 'bg-gradient-to-r from-blue-600 to-blue-400', 'UEFA Europa League': 'bg-gradient-to-r from-orange-600 to-black', 'Premier League': 'bg-gradient-to-r from-purple-600 to-blue-600', 'La Liga': 'bg-gradient-to-r from-red-600 to-yellow-600', 'Serie A': 'bg-gradient-to-r from-blue-600 to-green-600', 'Bundesliga': 'bg-gradient-to-r from-red-600 to-gray-600', 'Ligue 1': 'bg-gradient-to-r from-blue-600 to-red-600', 'Other': 'bg-gradient-to-r from-gray-600 to-gray-400' };
const leagueOrder = [ 'UEFA Champions League', 'UEFA Europa League', 'Premier League', 'La Liga', 'Serie A', 'Bundesliga', 'Ligue 1', 'Other' ];
export default function LiveScore() { const [liveScores, setLiveScores] = useState({}); const [error, setError] = useState<string | null>(null); const [isLoading, setIsLoading] = useState(true); const [lastTeamFetch, setLastTeamFetch] = useState(0); const [lastLeagueFetch, setLastLeagueFetch] = useState(0); const [expandedLeagues, setExpandedLeagues] = useState<{ [key: string]: boolean }>({});
const fetchLiveScores = async () => { setIsLoading(true); try { const response = await fetch(
${API_BASE_URL}/api/scores); if (!response.ok) throw new Error(HTTP error! status: ${response.status}); const data: LiveScores = await response.json(); setLiveScores(data); setError(null); } catch (error) { console.error("Fetching error:", error); setError(error instanceof Error ? error.message : String(error)); } finally { setIsLoading(false); } };const fetchTeamNames = async () => { try { const response = await fetch(
${API_BASE_URL}/api/team-names); if (!response.ok) throw new Error(HTTP error! status: ${response.status}); const data: { [key: number]: Team } = await response.json();setLiveScores(prevScores => { const updatedScores = { ...prevScores }; Object.keys(updatedScores).forEach(league => { updatedScores[league] = updatedScores[league].map(match => ({ ...match, homeTeam: data[match.homeTeam.id] || match.homeTeam, awayTeam: data[match.awayTeam.id] || match.awayTeam, })); }); return updatedScores; }); } catch (error) { console.error("Team fetching error:", error); }};
const fetchLeagueNames = async () => { try { const response = await fetch(
${API_BASE_URL}/api/league-names); if (!response.ok) throw new Error(HTTP error! status: ${response.status}); const data: { [key: string]: string } = await response.json(); setLiveScores(prevScores => { const updatedScores: LiveScores = {}; Object.keys(prevScores).forEach(oldLeague => { const newLeague = data[oldLeague] || oldLeague; updatedScores[newLeague] = prevScores[oldLeague]; }); return updatedScores; }); } catch (error) { console.error("League fetching error:", error); } };useEffect(() => { fetchLiveScores(); const intervalId = setInterval(() => { const now = Date.now(); if (now - lastTeamFetch > TEAM_REFRESH_DELAY) { fetchTeamNames(); setLastTeamFetch(now); } if (now - lastLeagueFetch > LEAGUE_REFRESH_DELAY) { fetchLeagueNames(); setLastLeagueFetch(now); } fetchLiveScores(); }, SCORE_REFRESH_DELAY);
return () => clearInterval(intervalId);}, [lastTeamFetch, lastLeagueFetch]);
const toggleLeagueExpansion = (league: string) => { setExpandedLeagues(prev => ({ ...prev, [league]: !prev[league] })); };
const MatchRow = ({ match }: { match: Match }) => ( {match.homeTeam.name} {match.score.fullTime.home ?? '-'} - {match.score.fullTime.away ?? '-'} {match.status === 'FINISHED' ? 'FT' :
${new Date(match.utcDate).toLocaleDateString([], { year: 'numeric', month: 'short', day: 'numeric' })} ${new Date(match.utcDate).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}} {match.awayTeam.name} );const LeagueCard = ({ league, matches }: { league: string, matches: Match[] }) => { const isExpanded = expandedLeagues[league]; const visibleMatches = isExpanded ? matches : matches.slice(0, 3);
return ( <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }} transition={{ duration: 0.3 }} className="mb-4" > <Card className="overflow-hidden shadow-lg hover:shadow-xl transition-shadow duration-300"> <CardHeader className={`${leagueColors[league] || 'bg-gradient-to-r from-gray-600 to-gray-400'} text-white cursor-pointer hover:bg-opacity-80 transition duration-200`} onClick={() => toggleLeagueExpansion(league)} style={{ cursor: 'pointer' }} > <CardTitle className="text-xl flex items-center justify-between"> <span>{league}</span> {isExpanded ? <ChevronUp size={20} /> : <ChevronDown size={20} />} </CardTitle> </CardHeader> <CardContent className="p-4"> {visibleMatches.map((match) => ( <MatchRow key={match.id} match={match} /> ))} {!isExpanded && matches.length > 3 && ( <div className="text-center mt-2 text-sm text-gray-500"> {matches.length - 3} more matches </div> )} </CardContent> </Card> </motion.div> );};
return ( Live Scores <motion.button whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }} onClick={() => window.location.reload()} className="p-2 rounded-full bg-blue-600 text-white hover:bg-blue-700 transition-colors duration-300" > </motion.button> {isLoading ? ( Array(3).fill(0).map((_, index) => ( )) ) : error ? ( Error: {error} ) : ( {leagueOrder.map(league => liveScores[league] && ( ) )} {Object.keys(liveScores).length === 0 && ( <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="text-center p-4 text-gray-600" > No live matches at the moment. </motion.div> )} )} ); } It is not showing league name like uefa champions league on my page
- Assistant
It sounds like you're encountering an issue where league names (e.g., "UEFA Champions League") are not displaying on your Live Scores page. Let's walk through potential causes and provide steps to troubleshoot and resolve the problem.
1. Understanding the Data Flow
Your component fetches live scores, team names, and league names from different API endpoints:
/api/scores: Fetches live match data categorized by leagues./api/team-names: Fetches updated team information./api/league-names: Fetches updated league names.
After fetching, the component updates the
liveScoresstate, which is then used to render league cards.2. Potential Causes and Solutions
A. Mismatch Between API Data and
leagueOrderCause: The league names returned by the API (especially after fetching and mapping via
fetchLeagueNames) might not match the names defined in yourleagueOrderarray. If there's a mismatch, the component won't render the correspondingLeagueCardbecause it iterates overleagueOrder.Solution:
-
Verify API Responses:
- Check
/api/scores: Ensure that the league keys are properly named. - Check
/api/league-names: Ensure that the mapping correctly translates old league names to the ones inleagueOrder.
- Check
-
Add Debugging Logs: Insert
console.logstatements to inspect the structure ofliveScoresafter each fetch:const fetchLiveScores = async () => { // ...existing code setLiveScores(data); console.log('Live Scores after fetching:', data); // Debugging // ... }; const fetchLeagueNames = async () => { // ...existing code setLiveScores(prevScores => { const updatedScores: LiveScores = {}; Object.keys(prevScores).forEach(oldLeague => { const newLeague = data[oldLeague] || oldLeague; updatedScores[newLeague] = prevScores[oldLeague]; }); console.log('Live Scores after league mapping:', updatedScores); // Debugging return updatedScores; }); // ... }; -
Adjust
leagueOrder: Ensure thatleagueOrderincludes all possible league names after mapping. If the API introduces new league names, update theleagueOrderarray accordingly.const leagueOrder = [ 'UEFA Champions League', 'UEFA Europa League', 'Premier League', 'La Liga', 'Serie A', 'Bundesliga', 'Ligue 1', 'Other', // Add any new league names here ];
B. Issues with
fetchLeagueNamesCause: The
fetchLeagueNamesfunction might be incorrectly mapping league names, leading to unexpected league keys that don't exist inleagueOrder.Solution:
-
Test Without
fetchLeagueNames: Temporarily disable thefetchLeagueNamescall to see if the league names appear correctly based on the original API data.useEffect(() => { fetchLiveScores(); const intervalId = setInterval(() => { const now = Date.now(); // if (now - lastTeamFetch > TEAM_REFRESH_DELAY) { // fetchTeamNames(); // setLastTeamFetch(now); // } // if (now - lastLeagueFetch > LEAGUE_REFRESH_DELAY) { // fetchLeagueNames(); // setLastLeagueFetch(now); // } fetchLiveScores(); }, SCORE_REFRESH_DELAY); return () => clearInterval(intervalId); }, [lastTeamFetch, lastLeagueFetch]);- If League Names Appear: The issue is with
fetchLeagueNames. Review the mapping logic. - If League Names Still Don't Appear: The issue might be elsewhere.
- If League Names Appear: The issue is with
-
Ensure Correct Mapping: Verify that the
fetchLeagueNamesresponse correctly maps old league names to new ones that exist inleagueOrder.const fetchLeagueNames = async () => { try { const response = await fetch(`${API_BASE_URL}/api/league-names`); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); const data: { [key: string]: string } = await response.json(); console.log('League Names Mapping:', data); // Debugging setLiveScores(prevScores => { const updatedScores: LiveScores = {}; Object.keys(prevScores).forEach(oldLeague => { const newLeague = data[oldLeague] || oldLeague; updatedScores[newLeague] = prevScores[oldLeague]; }); console.log('Live Scores after league mapping:', updatedScores); // Debugging return updatedScores; }); } catch (error) { console.error("League fetching error:", error); } };- Ensure: The
dataobject contains correct mappings and that the keys inupdatedScoresmatch those inleagueOrder.
- Ensure: The
C. Rendering Logic
Cause: The rendering part of the component relies on
leagueOrderto display leagues. IfliveScorescontains leagues not present inleagueOrder, they won't be rendered.Solution:
-
Render All Leagues: Modify the rendering logic to include all leagues, not just those in
leagueOrder. This ensures that even newly mapped leagues are displayed.<AnimatePresence> {leagueOrder.map(league => liveScores[league] && ( <LeagueCard key={league} league={league} matches={liveScores[league]} /> ) )} {Object.keys(liveScores).map(league => !leagueOrder.includes(league) && ( <LeagueCard key={league} league={league} matches={liveScores[league]} /> ) )} {Object.keys(liveScores).length === 0 && ( <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="text-center p-4 text-gray-600" > No live matches at the moment. </motion.div> )} </AnimatePresence> -
Optional: Combine and Sort: Alternatively, create a combined and sorted list to render leagues:
const sortedLeagues = [ ...leagueOrder.filter(league => liveScores[league]), ...Object.keys(liveScores).filter(league => !leagueOrder.includes(league)) ]; <AnimatePresence> {sortedLeagues.map(league => ( <LeagueCard key={league} league={league} matches={liveScores[league]} /> ))} {Object.keys(liveScores).length === 0 && ( <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="text-center p-4 text-gray-600" > No live matches at the moment. </motion.div> )} </AnimatePresence>
D. CSS and Styling Issues
Cause: The league name might be rendering but not visible due to CSS issues, such as text color blending with the background.
Solution:
-
Inspect Elements:
- Use browser developer tools to inspect the
CardTitleelement and verify that theleagueprop is correctly rendered. - Check if the text is present but styled incorrectly (e.g., same color as the background).
- Use browser developer tools to inspect the
-
Ensure Proper Styling:
- Verify that the
leagueColorsmapping provides sufficient contrast for the text. - For example, if a gradient background is dark, ensure the text color is set to
text-white.
<CardHeader className={`${leagueColors[league] || 'bg-gradient-to-r from-gray-600 to-gray-400'} text-white cursor-pointer hover:bg-opacity-80 transition duration-200`} onClick={() => toggleLeagueExpansion(league)} > <CardTitle className="text-xl flex items-center justify-between"> <span>{league}</span> {isExpanded ? <ChevronUp size={20} /> : <ChevronDown size={20} />} </CardTitle> </CardHeader>- Ensure that
text-whiteis applied and that the background gradients don't obscure the text.
- Verify that the
3. Additional Recommendations
A. Error Handling and User Feedback
Improve user feedback by providing more detailed error messages and handling different error scenarios gracefully.
{isLoading ? ( // ...existing skeletons ) : error ? ( <Card className="bg-red-100 text-red-700 p-4"> <CardContent> <p>Error fetching live scores:</p> <p>{error}</p> </CardContent> </Card> ) : ( // ...existing rendering logic )}B. Optimize Fetch Intervals
Ensure that your fetch intervals don't cause unnecessary re-renders or API overloads. Consider using separate intervals for different data types or leveraging a more sophisticated state management approach.
C. Use Environment Variables
Avoid hardcoding the
API_BASE_URL. Utilize environment variables for better flexibility and security, especially when deploying to production.const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:5000';Ensure you've set up environment variables correctly in your project configuration.
4. Example: Simplified Rendering Without
leagueOrderIf aligning league names with
leagueOrderproves too cumbersome, consider rendering leagues directly fromliveScoreswithout relying on a predefined order. You can still sort them based on a dynamic criteria if needed.<AnimatePresence> {Object.keys(liveScores).length > 0 ? ( Object.keys(liveScores).map(league => ( <LeagueCard key={league} league={league} matches={liveScores[league]} /> )) ) : ( <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="text-center p-4 text-gray-600" > No live matches at the moment. </motion.div> )} </AnimatePresence>5. Final Checklist
- Verify API Responses: Ensure all endpoints return the expected data structures and values.
- Check State Updates: Use
console.logto trace howliveScoresupdates after each fetch. - Align League Names: Ensure that league names after mapping match those in your rendering logic.
- Inspect CSS: Confirm that league names are not hidden or styled incorrectly.
- Handle Errors Gracefully: Provide clear feedback to users in case of errors.
- Optimize Performance: Ensure that fetch intervals and state updates are efficient.
By following these steps, you should be able to identify and resolve the issue with league names not displaying on your Live Scores page. If after these steps the problem persists, consider sharing additional details or specific API responses for more targeted assistance.