'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> )} )} ); } This is my LiveScore.tsx I want to improve it's design and also don't want to use useEffect
- Assistant
To enhance the design of your
LiveScore.tsxcomponent and eliminate the use ofuseEffectfor data fetching, I recommend leveraging React Query (now known as TanStack Query). React Query simplifies data fetching, caching, and synchronization, allowing you to manage server state more efficiently without manually handling lifecycle methods likeuseEffect.Additionally, we can improve the UI/UX by incorporating better design practices, enhancing responsiveness, and refining animations and transitions.
Below is a step-by-step guide to refactoring your component:
-
Install React Query
First, install React Query using npm or yarn:
npm install @tanstack/react-queryor
yarn add @tanstack/react-query -
Set Up React Query's QueryClient
Wrap your application with the
QueryClientProviderto provide React Query's context. This is typically done in your main application file (e.g.,App.tsxorindex.tsx):// src/App.tsx import React from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import LiveScore from './components/LiveScore'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> <LiveScore /> </QueryClientProvider> ); } export default App; -
Refactor
LiveScore.tsxto Use React QueryUpdate your
LiveScore.tsxto utilize React Query for data fetching. This removes the need foruseEffectand simplifies the data handling logic.'use client'; import React, { useState } 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'; import { useQuery } from '@tanstack/react-query'; import axios from 'axios'; const API_BASE_URL = 'http://localhost:5000'; const SCORE_REFRESH_INTERVAL = 60000; // 1 minute const TEAM_REFRESH_INTERVAL = 300000; // 5 minutes const LEAGUE_REFRESH_INTERVAL = 3600000; // 1 hour 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 [expandedLeagues, setExpandedLeagues] = useState<{ [key: string]: boolean; }>({}); // Fetch Live Scores const { data: liveScores, isLoading, isError, error, refetch, } = useQuery<LiveScores, Error>( ['liveScores'], async () => { const response = await axios.get( `${API_BASE_URL}/api/scores` ); return response.data; }, { refetchInterval: SCORE_REFRESH_INTERVAL, staleTime: SCORE_REFRESH_INTERVAL, } ); // Fetch Team Names const { data: teamData } = useQuery< { [key: number]: Team }, Error >( ['teamNames'], async () => { const response = await axios.get( `${API_BASE_URL}/api/team-names` ); return response.data; }, { refetchInterval: TEAM_REFRESH_INTERVAL, staleTime: TEAM_REFRESH_INTERVAL, } ); // Fetch League Names const { data: leagueData } = useQuery< { [key: string]: string }, Error >( ['leagueNames'], async () => { const response = await axios.get( `${API_BASE_URL}/api/league-names` ); return response.data; }, { refetchInterval: LEAGUE_REFRESH_INTERVAL, staleTime: LEAGUE_REFRESH_INTERVAL, } ); // Merge Team and League Data const processedLiveScores: LiveScores = React.useMemo(() => { if (!liveScores || !teamData || !leagueData) return {}; const updatedScores: LiveScores = {}; Object.keys(liveScores).forEach((oldLeague) => { const newLeague = leagueData[oldLeague] || oldLeague; updatedScores[newLeague] = updatedScores[newLeague] || []; liveScores[oldLeague].forEach((match) => { updatedScores[newLeague].push({ ...match, homeTeam: teamData[match.homeTeam.id] || match.homeTeam, awayTeam: teamData[match.awayTeam.id] || match.awayTeam, }); }); }); return updatedScores; }, [liveScores, teamData, leagueData]); const toggleLeagueExpansion = (league: string) => { setExpandedLeagues((prev) => ({ ...prev, [league]: !prev[league], })); }; const MatchRow = ({ match }: { match: Match }) => ( <div className="flex justify-between items-center py-2 border-b last:border-b-0"> <div className="flex items-center space-x-2 w-5/12"> <img src={match.homeTeam.crest} alt={match.homeTeam.name} className="w-4 h-4" /> <span className="font-semibold text-sm"> {match.homeTeam.name} </span> </div> <div className="flex flex-col items-center w-2/12"> <div className="text-sm font-bold"> {match.score.fullTime.home ?? '-'} -{' '} {match.score.fullTime.away ?? '-'} </div> <div className="text-xs text-gray-500"> {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' } )}`} </div> </div> <div className="flex items-center justify-end space-x-2 w-5/12"> <span className="font-semibold text-sm"> {match.awayTeam.name} </span> <img src={match.awayTeam.crest} alt={match.awayTeam.name} className="w-4 h-4" /> </div> </div> ); 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)} > <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 ( <div className="space-y-4 max-w-3xl mx-auto p-4"> <div className="flex justify-between items-center mb-6"> <h2 className="text-3xl font-bold text-gray-800"> Live Scores </h2> <motion.button whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }} onClick={() => refetch()} className="p-2 rounded-full bg-blue-600 text-white hover:bg-blue-700 transition-colors duration-300 focus:outline-none" aria-label="Refresh Scores" > <RefreshCw size={20} /> </motion.button> </div> {isLoading ? ( Array(3) .fill(0) .map((_, index) => ( <Skeleton key={index} className="h-40 w-full mb-4 rounded" /> )) ) : isError ? ( <Card className="bg-red-100 text-red-700 p-4"> <CardContent> <p>Error: {error.message}</p> <button onClick={() => refetch()} className="mt-2 px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 transition-colors duration-200" > Retry </button> </CardContent> </Card> ) : ( <AnimatePresence> {leagueOrder.map((league) => processedLiveScores[league] ? ( <LeagueCard key={league} league={league} matches={processedLiveScores[league]} /> ) : null )} {Object.keys(processedLiveScores).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> )} </div> ); } -
Enhancements and Design Improvements
-
Responsive Design: Increased the maximum width to
max-w-3xland added padding to ensure the component looks good on various screen sizes. -
Improved Loading Skeletons: Added
roundedclasses to the Skeleton components for smoother aesthetics. -
Enhanced Error Handling: Included a retry button when an error occurs, allowing users to manually refetch data.
-
Accessibility: Added
aria-labelto the refresh button for better accessibility. -
Transitions and Animations: Maintained
framer-motionanimations for smooth transitions when expanding leagues and handling component mount/unmount. -
Button Styling: Enhanced the refresh button’s focus state and hover effects for better user experience.
-
-
Optional: Customize QueryClient Settings
You can further customize the
QueryClientto set global settings like default refetch intervals, retry strategies, etc. For example:// src/App.tsx import React from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import LiveScore from './components/LiveScore'; const queryClient = new QueryClient({ defaultOptions: { queries: { retry: 2, // Retry failed requests twice refetchOnWindowFocus: false, // Do not refetch on window focus }, }, }); function App() { return ( <QueryClientProvider client={queryClient}> <LiveScore /> </QueryClientProvider> ); } export default App; -
Considerations for API Data Structure
Ensure that your backend APIs (
/api/scores,/api/team-names, and/api/league-names) return consistent and reliable data structures as expected by the frontend. Proper error handling and data validation on the server side can prevent issues on the client side. -
Further UI Enhancements
-
Dark Mode Support: Incorporate dark mode styles to enhance user experience for users who prefer it.
-
Tooltips and Hover Effects: Add tooltips to team names or crests to provide additional information.
-
Pagination or Infinite Scroll: If there are many matches, consider adding pagination or infinite scrolling to manage content load effectively.
-
Custom Icons and Illustrations: Use custom SVGs or illustrations to make the UI more engaging.
-
-
Performance Optimization
-
Memoization: Utilize
React.useMemoto memoize computed values, such asprocessedLiveScores, to prevent unnecessary recalculations on every render. -
Lazy Loading Images: Implement lazy loading for team crest images to improve initial load performance.
Example of lazy loading images:
<img src={match.homeTeam.crest} alt={match.homeTeam.name} className="w-4 h-4" loading="lazy" /> -
-
Final Code Review
Ensure that the final implementation adheres to best practices, including:
-
TypeScript Type Safety: Verify that all TypeScript interfaces accurately represent the data structures.
-
Clean and Readable Code: Maintain consistent formatting and clear variable naming for maintainability.
-
Component Reusability: Break down the component into smaller, reusable components if it grows in complexity.
-
By adopting React Query for data management and implementing the suggested design improvements, your
LiveScorecomponent will become more efficient, responsive, and user-friendly. -