To enable navigation to a player’s detailed page using their unique playerId, you need to fetch the playerId asynchronously based on the player's name using the searchPlayers function. Since React components cannot handle asynchronous operations directly within the JSX, you'll need to manage this logic within useEffect hooks and maintain the retrieved playerIds in the component's state.
Below is a step-by-step guide to achieve this, including updated code snippets for your app/league/page.tsx component:
-
Maintain a Mapping of Player Names to IDs
Create a state to store the mapping between player names and their corresponding playerId. This map will be used to link to the player’s detailed page.
-
Fetch Player IDs After Fetching League Data
Once the leagueData is fetched, extract unique player names from the topScorers and fetch their playerIds using the searchPlayers function. Store these IDs in the mapping state.
-
Update the JSX to Use the Retrieved playerIds
Use the mapping to generate the correct URLs for each player's detail page.
Here's how you can implement these steps:
1. Update app/league/page.tsx
// app/league/page.tsx
'use client'; // Retain if interactivity is required; otherwise, consider Server Components
import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import Image from 'next/image';
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 {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import Link from 'next/link';
import { toast } from 'react-toastify';
import { searchPlayers } from "../../utils/api";
// Interfaces
interface Team { /* ... */ }
interface League { /* ... */ }
interface Standing { /* ... */ }
interface TopScorer { /* ... */ }
interface Match { /* ... */ }
interface LeagueData { /* ... */ }
export default function LeaguePage() {
const searchParams = useSearchParams();
const code = searchParams.get('code')?.toUpperCase(); // Get 'code' from query parameters and ensure it's uppercase
const [leagueData, setLeagueData] = useState<LeagueData | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<'Teams' | 'Standings' | 'Top Scorers' | 'Matches'>('Teams');
// State to map player names to their IDs
const [playerIdMap, setPlayerIdMap] = useState<{ [name: string]: string }>({});
const [isPlayerIdLoading, setIsPlayerIdLoading] = useState<boolean>(false);
useEffect(() => {
const fetchLeagueData = async () => {
try {
if (!code) {
throw new Error('No league code provided');
}
const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/league/${code}`); // Use environment variable
if (!response.ok) {
if (response.status === 404) {
throw new Error('League not found');
}
throw new Error('Failed to fetch league data');
}
const data: LeagueData = await response.json();
setLeagueData(data);
} catch (error) {
console.error('Error fetching league data:', error);
setError(error instanceof Error ? error.message : 'An error occurred');
} finally {
setIsLoading(false);
}
};
if (code) {
fetchLeagueData();
} else {
setIsLoading(false);
setError('No league code provided');
}
}, [code]);
// Fetch player IDs after leagueData is set
useEffect(() => {
const fetchPlayerIds = async () => {
if (leagueData && leagueData.topScorers) {
setIsPlayerIdLoading(true);
const uniqueNames = Array.from(new Set(leagueData.topScorers.map(scorer => scorer.player.name)));
const promises = uniqueNames.map(async (name) => {
try {
const players = await searchPlayers(name);
// Assuming the API returns a list of players with a unique player_id
if (players.length > 0) {
// You might need to adjust the property name based on your API response
return { name, id: players[0].player_id };
} else {
console.warn(`No player found for name: ${name}`);
return { name, id: '' };
}
} catch (err) {
console.error(`Error searching player "${name}":`, err);
return { name, id: '' };
}
});
try {
const results = await Promise.all(promises);
const map: { [key: string]: string } = {};
results.forEach(result => {
map[result.name] = result.id;
});
setPlayerIdMap(map);
} catch (err) {
console.error('Error fetching player IDs:', err);
toast.error('Failed to fetch some player IDs.');
} finally {
setIsPlayerIdLoading(false);
}
}
};
fetchPlayerIds();
}, [leagueData]);
if (isLoading || isPlayerIdLoading) {
return <LeagueSkeleton />;
}
if (error) {
return (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
);
}
if (!leagueData) {
return (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Not Found</AlertTitle>
<AlertDescription>League not found</AlertDescription>
</Alert>
);
}
const { league, teams, standings, topScorers, matches } = leagueData;
return (
<div className="container mx-auto px-4 py-8">
{/* League Information Card */}
<Card className="mb-8">
<CardHeader className="flex flex-row items-center space-x-4">
<div className="relative w-16 h-16">
<Image
src={league.emblem}
alt={`${league.name} emblem`}
width={64}
height={64}
className="rounded-full object-contain"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.src = '/placeholder.svg';
}}
/>
</div>
<div>
<CardTitle>{league.name}</CardTitle>
<p className="text-sm text-gray-500">{league.area.name}</p>
</div>
</CardHeader>
<CardContent>
<p><strong>Current Season:</strong> {league.currentSeason.startDate} to {league.currentSeason.endDate}</p>
<p><strong>Current Matchday:</strong> {league.currentSeason.currentMatchday}</p>
</CardContent>
</Card>
{/* Tabs Navigation */}
<div className="mb-6 flex space-x-4" role="tablist" aria-label="League Data Tabs">
<Button
variant={activeTab === 'Teams' ? 'default' : 'outline'}
onClick={() => setActiveTab('Teams')}
aria-selected={activeTab === 'Teams'}
role="tab"
>
Teams
</Button>
<Button
variant={activeTab === 'Standings' ? 'default' : 'outline'}
onClick={() => setActiveTab('Standings')}
aria-selected={activeTab === 'Standings'}
role="tab"
>
Standings
</Button>
<Button
variant={activeTab === 'Top Scorers' ? 'default' : 'outline'}
onClick={() => setActiveTab('Top Scorers')}
aria-selected={activeTab === 'Top Scorers'}
role="tab"
>
Top Scorers
</Button>
<Button
variant={activeTab === 'Matches' ? 'default' : 'outline'}
onClick={() => setActiveTab('Matches')}
aria-selected={activeTab === 'Matches'}
role="tab"
>
Matches
</Button>
</div>
{/* Conditional Rendering Based on Active Tab */}
{activeTab === 'Teams' && (
<>
<h2 className="text-2xl font-bold mb-4">Teams</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{teams.map((team) => (
<Card key={team.id} className="shadow-md">
<CardHeader className="flex flex-row items-center space-x-4">
<div className="relative w-12 h-12">
<Image
src={team.crest}
alt={`${team.name} crest`}
width={48}
height={48}
className="rounded-full object-contain"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.src = '/placeholder.svg';
}}
/>
</div>
<CardTitle className="text-lg">{team.name}</CardTitle>
</CardHeader>
<CardContent>
<p><strong>Venue:</strong> {team.venue}</p>
<p><strong>Founded:</strong> {team.founded}</p>
<p><strong>Club Colors:</strong> {team.clubColors}</p>
</CardContent>
</Card>
))}
</div>
</>
)}
{activeTab === 'Standings' && (
<>
<h2 className="text-2xl font-bold mb-4">Standings</h2>
<div className="overflow-x-auto">
<Table className="min-w-full">
<TableHeader>
<TableRow>
<TableHead className="px-6 py-3">Pos</TableHead>
<TableHead className="px-6 py-3">Team</TableHead>
<TableHead className="px-6 py-3">P</TableHead>
<TableHead className="px-6 py-3">W</TableHead>
<TableHead className="px-6 py-3">D</TableHead>
<TableHead className="px-6 py-3">L</TableHead>
<TableHead className="px-6 py-3">GF</TableHead>
<TableHead className="px-6 py-3">GA</TableHead>
<TableHead className="px-6 py-3">GD</TableHead>
<TableHead className="px-6 py-3">Pts</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{standings.map((standing) => (
<TableRow key={standing.position}>
<TableCell className="px-6 py-4">{standing.position}</TableCell>
<TableCell className="px-6 py-4 flex items-center space-x-2">
<Image
src={standing.team.crest}
alt={`${standing.team.name} crest`}
width={24}
height={24}
className="rounded-full object-contain"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.src = '/placeholder.svg';
}}
/>
<span>{standing.team.name}</span>
</TableCell>
<TableCell className="px-6 py-4">{standing.playedGames}</TableCell>
<TableCell className="px-6 py-4">{standing.won}</TableCell>
<TableCell className="px-6 py-4">{standing.draw}</TableCell>
<TableCell className="px-6 py-4">{standing.lost}</TableCell>
<TableCell className="px-6 py-4">{standing.goalsFor}</TableCell>
<TableCell className="px-6 py-4">{standing.goalsAgainst}</TableCell>
<TableCell className="px-6 py-4">{standing.goalDifference}</TableCell>
<TableCell className="px-6 py-4">{standing.points}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</>
)}
{activeTab === 'Top Scorers' && (
<>
<h2 className="text-2xl font-bold mb-4">Top Scorers</h2>
<div className="overflow-x-auto">
<Table className="min-w-full">
<TableHeader>
<TableRow>
<TableHead className="px-6 py-3">#</TableHead>
<TableHead className="px-6 py-3">Player</TableHead>
<TableHead className="px-6 py-3">Team</TableHead>
<TableHead className="px-6 py-3">Goals</TableHead>
<TableHead className="px-6 py-3">Assists</TableHead>
<TableHead className="px-6 py-3">Penalties</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{topScorers.map((scorer, index) => (
<TableRow key={`${scorer.player.name}-${index}`}>
<TableCell className="px-6 py-4">{index + 1}</TableCell>
<TableCell className="px-6 py-4 flex items-center space-x-2">
<Image
src={scorer.team.crest}
alt={`${scorer.team.name} crest`}
width={24}
height={24}
className="rounded-full object-contain"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.src = '/placeholder.svg';
}}
/>
{playerIdMap[scorer.player.name] ? (
<Link
href={`/players/${playerIdMap[scorer.player.name]}`}
className="text-blue-500 hover:underline"
>
{scorer.player.name}
</Link>
) : (
<span className="text-gray-500">{scorer.player.name}</span>
)}
</TableCell>
<TableCell className="px-6 py-4">{scorer.team.name}</TableCell>
<TableCell className="px-6 py-4">{scorer.goals}</TableCell>
<TableCell className="px-6 py-4">{scorer.assists}</TableCell>
<TableCell className="px-6 py-4">{scorer.penalties}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</>
)}
{activeTab === 'Matches' && (
<>
<h2 className="text-2xl font-bold mb-4">Upcoming Matches</h2>
<div className="overflow-x-auto">
<Table className="min-w-full">
<TableHeader>
<TableRow>
{/* <TableHead className="px-6 py-3">Match ID</TableHead> */}
<TableHead className="px-6 py-3">Date</TableHead>
<TableHead className="px-6 py-3">Status</TableHead>
<TableHead className="px-6 py-3">Matchday</TableHead>
<TableHead className="px-6 py-3">Home Team</TableHead>
<TableHead className="px-6 py-3">Away Team</TableHead>
<TableHead className="px-6 py-3">Score</TableHead>
<TableHead className="px-6 py-3">Odds</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{matches.map((match) => (
<TableRow key={match.id}>
{/* <TableCell className="px-6 py-4">{match.id}</TableCell> */}
<TableCell className="px-6 py-4">{new Date(match.utcDate).toLocaleString()}</TableCell>
<TableCell className="px-6 py-4">{match.status}</TableCell>
<TableCell className="px-6 py-4">{match.matchday}</TableCell>
<TableCell className="px-6 py-4 flex items-center space-x-2">
<Image
src={match.awayTeam.crest}
alt={`${match.awayTeam.name} crest`}
width={24}
height={24}
className="rounded-full object-contain"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.src = '/placeholder.svg';
}}
/>
<span>{match.awayTeam.name}</span>
</TableCell>
<TableCell className="px-6 py-4">
{match.score.fullTime.home !== null && match.score.fullTime.away !== null
? `${match.score.fullTime.home} - ${match.score.fullTime.away}`
: 'N/A'}
</TableCell>
<TableCell className="px-6 py-4">
Home Win: {match.odds.homeWin} | Draw: {match.odds.draw} | Away Win: {match.odds.awayWin}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</>
)}
</div>
);
}
function LeagueSkeleton() {
return (
<div className="container mx-auto px-4 py-8">
{/* League Information Skeleton */}
<Card className="mb-8">
<CardHeader className="flex flex-row items-center space-x-4">
<Skeleton className="w-16 h-16 rounded-full" />
<div>
<Skeleton className="h-6 w-40 mb-2" />
<Skeleton className="h-4 w-24" />
</div>
</CardHeader>
<CardContent>
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-3/4" />
</CardContent>
</Card>
{/* Tabs Skeleton */}
<div className="mb-6 flex space-x-4">
<Skeleton className="h-10 w-24 rounded" />
<Skeleton className="h-10 w-24 rounded" />
<Skeleton className="h-10 w-24 rounded" />
<Skeleton className="h-10 w-24 rounded" /> {/* Matches Tab */}
</div>
{/* Content Skeleton */}
<Skeleton className="h-8 w-40 mb-4" />
{/* Depending on which tab is active, render different skeletons */}
{/* For simplicity, here's a generic content skeleton */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{[...Array(6)].map((_, index) => (
<Card key={index}>
<CardHeader className="flex flex-row items-center space-x-4">
<Skeleton className="w-12 h-12 rounded-full" />
<Skeleton className="h-6 w-32" />
</CardHeader>
<CardContent>
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-3/4 mb-2" />
<Skeleton className="h-4 w-1/2" />
</CardContent>
</Card>
))}
</div>
{/* Matches Skeleton */}
<Skeleton className="h-8 w-40 mb-4 mt-8" />
<div className="overflow-x-auto">
<Skeleton className="h-12 w-full mb-2" /> {/* Table Header */}
{[...Array(5)].map((_, index) => (
<div key={index} className="flex space-x-4 mb-2">
<Skeleton className="h-6 w-12" />
<Skeleton className="h-6 w-24" />
<Skeleton className="h-6 w-24" />
<Skeleton className="h-6 w-24" />
<Skeleton className="h-6 w-24" />
<Skeleton className="h-6 w-24" />
<Skeleton className="h-6 w-24" />
</div>
))}
</div>
</div>
)
}
2. Explanation of Changes
-
State Management for Player IDs
// State to map player names to their IDs
const [playerIdMap, setPlayerIdMap] = useState<{ [name: string]: string }>({});
const [isPlayerIdLoading, setIsPlayerIdLoading] = useState<boolean>(false);
playerIdMap: Stores a mapping from player names to their unique playerIds.
isPlayerIdLoading: Indicates whether the player IDs are still being fetched.
-
Fetching Player IDs After League Data is Loaded
useEffect(() => {
const fetchPlayerIds = async () => {
if (leagueData && leagueData.topScorers) {
setIsPlayerIdLoading(true);
const uniqueNames = Array.from(new Set(leagueData.topScorers.map(scorer => scorer.player.name)));
const promises = uniqueNames.map(async (name) => {
try {
const players = await searchPlayers(name);
// Assuming the API returns a list of players with a unique player_id
if (players.length > 0) {
// You might need to adjust the property name based on your API response
return { name, id: players[0].player_id };
} else {
console.warn(`No player found for name: ${name}`);
return { name, id: '' };
}
} catch (err) {
console.error(`Error searching player "${name}":`, err);
return { name, id: '' };
}
});
try {
const results = await Promise.all(promises);
const map: { [key: string]: string } = {};
results.forEach(result => {
map[result.name] = result.id;
});
setPlayerIdMap(map);
} catch (err) {
console.error('Error fetching player IDs:', err);
toast.error('Failed to fetch some player IDs.');
} finally {
setIsPlayerIdLoading(false);
}
}
};
fetchPlayerIds();
}, [leagueData]);
- Extract Unique Player Names: This avoids redundant API calls for players with the same name.
- Fetch IDs Concurrently: Uses
Promise.all to fetch all player IDs concurrently.
- Handle Errors Gracefully: Logs errors and skips players not found, ensuring the UI remains stable.
-
Conditional Rendering Based on Loading States
if (isLoading || isPlayerIdLoading) {
return <LeagueSkeleton />;
}
- Displays a loading skeleton while either the league data or player IDs are being fetched.
-
Updating the Top Scorers Table to Include Links
3. Optimizing the User Experience
- Handling Missing Player IDs: Players without a found
playerId are shown without a link. You might want to add additional indicators or error messages if desired.
- Caching Player IDs: To optimize performance, especially if the same players appear frequently, consider caching the
playerIdMap in a higher context or using a state management library like Redux or Zustand.
4. Ensuring player_id Exists in API Responses
Ensure that the searchPlayers function returns an array of players with a unique identifier (e.g., player_id). If your API uses a different property name, adjust the code accordingly.
For example, if your player object uses id instead of player_id, update the mapping logic:
return { name, id: players[0].id };
5. Updated searchPlayers Function (If Necessary)
Ensure that your searchPlayers function correctly maps the API response to include the necessary player_id. Here's how it might look:
// utils/api.ts
import axios from 'axios';
import { Player, Match } from '../types';
// Ensure to set NEXT_PUBLIC_API_BASE_URL in your .env.local
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:5000/api';
/**
* Search players by name.
* @param query - Player name query.
* @returns Promise resolving to an array of Player objects.
*/
export const searchPlayers = async (query: string): Promise<Player[]> => {
try {
const response = await axios.get(`${API_BASE_URL}/players/searchPlayers`, {
params: { q: query },
});
return response.data.players.map((p: any) => ({
...p,
player_id: p.id, // Adjust based on your API's structure
}));
} catch (error: any) {
console.error('Search Players Error:', error);
throw error.response?.data?.error || 'Error searching players';
}
};
// ... other functions
Ensure that each Player object includes a player_id property that uniquely identifies the player.
6. Example of the Player Interface
Make sure your Player interface in types includes the necessary fields:
// types.ts
export interface Player {
player_id: string;
name: string;
position: string;
team: string;
photo_url?: string;
// ... other fields
}
7. Handling Navigation in the Player Page
Ensure your player page (app/players/[id]/page.tsx) correctly handles cases where an invalid or missing playerId is provided.
Final Thoughts
By implementing the above changes, you enable your application to dynamically fetch and associate player IDs with their names, allowing users to navigate seamlessly to individual player pages. This approach ensures that your UI remains responsive and that asynchronous data fetching does not interfere with the rendering logic.
Note: Depending on the size of your topScorers data, fetching player IDs client-side might introduce some delays. For larger datasets or performance-critical applications, consider optimizing the API to include playerIds directly in the topScorers data or implementing server-side data fetching strategies.