To restructure your Next.js application by removing the dynamic [code] route and transitioning to a single league.tsx file that handles routing based on selections from LeagueSelector.tsx, follow the detailed steps below. This approach uses query parameters to pass the league code instead of dynamic routing.
Overview
-
Remove the Dynamic Route:
- Delete the
/app/league/[code] folder and its page.tsx file.
-
Create a Single League Page:
- Create a new
/app/league/page.tsx file that handles the league code via query parameters.
-
Update the LeagueSelector Component:
- Modify the
LeagueSelector.tsx to navigate to the new league page using query parameters.
-
Ensure Backend Routes Are Correct:
- Confirm that your backend API routes are correctly set up to handle requests from the frontend.
-
Optimize Fetch Requests:
- Use environment variables for API URLs to make your application more flexible and secure.
Let's go through each step in detail.
1. Remove the Dynamic Route
First, delete the existing dynamic route that handles /league/[code].
This will remove the dynamic routing that was previously handling league codes.
2. Create a Single League Page
Next, create a new page.tsx file within the league directory that will handle all league-related displays based on query parameters.
-
Create the File:
/app/league/page.tsx
-
Implement the Component:
Here's the complete implementation of the new LeaguePage component using query parameters:
// /app/league/page.tsx
'use client'
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'
interface Team {
id: number
name: string
shortName: string
tla: string
crest: string
venue: string
website: string
founded: number
clubColors: string
}
interface League {
id: number
name: string
code: string
type: string
emblem: string
area: {
id: number
name: string
code: string
flag: string
}
currentSeason: {
id: number
startDate: string
endDate: string
currentMatchday: number
winner: null | string
}
}
interface LeagueData {
league: League
teams: Team[]
}
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)
useEffect(() => {
const fetchLeagueData = async () => {
try {
if (!code) {
throw new Error('No league code provided')
}
const response = await fetch(`/api/league/${code}`)
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])
if (isLoading) {
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 } = leagueData
return (
<div className="container mx-auto px-4 py-8">
<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>
<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}>
<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>
</div>
)
}
function LeagueSkeleton() {
return (
<div className="container mx-auto px-4 py-8">
<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>
<Skeleton className="h-8 w-40 mb-4" />
<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>
</div>
)
}
Explanation:
-
useSearchParams:
Utilizes the useSearchParams hook from next/navigation to access query parameters from the URL. This replaces useParams, which is used for dynamic routes.
-
Fetching Data:
The component fetches league data based on the code query parameter. If no code is provided or if there's an error during fetching, appropriate error messages are displayed.
-
Error Handling:
Comprehensive error handling ensures that users are informed if something goes wrong, such as missing league codes or failed fetch requests.
-
Skeleton Loading:
Displays skeleton components while data is being fetched, providing a better user experience during load times.
3. Update the LeagueSelector Component
Modify the LeagueSelector.tsx to navigate to the new league page using query parameters instead of dynamic routes.
// /app/components/LeagueSelector.tsx
'use client'
import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { AlertCircle } from 'lucide-react'
import Link from 'next/link'
import Image from 'next/image'
interface League {
id: number
name: string
code: string
type: string
emblem: string
area: {
id: number
name: string
code: string
flag: string | null
}
}
interface LeaguesResponse {
count: number
leagues: League[]
}
export default function LeagueSelector() {
const [leagues, setLeagues] = useState<League[]>([])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const fetchLeagues = async () => {
try {
const response = await fetch('/api/leagues') // Use relative path
if (!response.ok) {
throw new Error('Failed to fetch leagues')
}
const data: LeaguesResponse = await response.json()
setLeagues(data.leagues)
} catch (error) {
console.error('Error fetching leagues:', error)
setError('Failed to load leagues. Please try again later.')
} finally {
setIsLoading(false)
}
}
fetchLeagues()
}, [])
if (isLoading) {
return <LeagueSkeleton />
}
if (error) {
return (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
)
}
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{leagues.map((league) => (
<Link
href={`/league?code=${encodeURIComponent(league.code)}`} // Pass code as query parameter
key={league.code}
className="focus:outline-none focus:ring-2 focus:ring-blue-500 rounded-lg"
>
<Card className="hover:shadow-lg transition-shadow duration-300">
<CardHeader className="flex flex-row items-center space-x-4">
<div className="relative w-12 h-12">
<Image
src={league.emblem}
alt={`${league.name} emblem`}
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">{league.name}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-gray-500">{league.area.name}</p>
<p className="text-sm text-gray-500">{league.type}</p>
</CardContent>
</Card>
</Link>
))}
</div>
)
}
function LeagueSkeleton() {
return (
<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" />
</CardContent>
</Card>
))}
</div>
)
}
Key Changes:
-
Link Modification:
-
Fetch API URL:
- Changed from
http://localhost:5000/api/leagues to /api/leagues to use a relative path. This ensures it works correctly in different environments (development, production).
-
Encoding the Code:
- Ensures that the league code is properly URL-encoded to handle any special characters.
4. Ensure Backend Routes Are Correct
Your backend routes appear to be correctly set up to handle the frontend requests. However, ensure the following:
-
Base URL Consistency:
-
CORS Configuration:
- Your backend already includes CORS setup:
app.use(
cors({
origin: "http://localhost:3000", // Replace with your frontend URL
methods: ["GET", "POST", "PUT", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"],
})
)
- If deploying to production, update the
origin to match your frontend's URL.
-
Environment Variables:
- Ensure that your backend has the correct
API_FOOTBALL_KEY1 and MONGO_URL environment variables set.
5. Optimize Fetch Requests with Environment Variables
To make your application more flexible and secure, avoid hardcoding API URLs. Instead, use environment variables.
-
Set Up Environment Variables:
Create a .env.local file at the root of your project:
NEXT_PUBLIC_API_BASE_URL=http://localhost:5000/api
- Explanation:
Prefixing with NEXT_PUBLIC_ makes the variable available on the client side.
-
Update Fetch Requests:
Update both LeaguePage and LeagueSelector to use the environment variable.
-
LeaguePage:
const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/league/${code}`)
-
LeagueSelector:
const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/leagues`)
-
Ensure Proper Configuration:
- Restart your development server after adding environment variables.
- These variables can be replaced with production URLs during deployment.
Final Directory Structure
Your project structure should now resemble the following:
/app
/league
page.tsx
/components
LeagueSelector.tsx
/api
/leagues
[GET] /api/leagues
/league
[GET] /api/league/:code
/controllers
leagueController.js
leaguesController.js
/routes
leagueRoutes.js
leaguesRoutes.js
...
Summary
By following these steps, you've successfully:
- Removed the dynamic
[code] routing and replaced it with a query parameter-based approach.
- Created a unified
LeaguePage component that fetches league data based on the code query parameter.
- Updated the
LeagueSelector component to navigate using query parameters instead of dynamic routes.
- Ensured backend routes are correctly handling the frontend requests with proper CORS configuration.
- Optimized your fetch requests by using environment variables for better flexibility and security.
This setup enhances the maintainability of your application and aligns with your requirement to remove the dynamic routing mechanism. If you encounter any issues or need further customization, feel free to ask!