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}/searchPlayers, {
params: { q: query },
});
return response.data.players;
} catch (error: any) {
console.error('Search Players Error:', error);
throw error.response?.data?.error || 'Error searching players';
}
};
/*
Get detailed information about a specific player by ID.
@param playerId - Unique identifier of the player.
@returns Promise resolving to a Player object.
/
export const getPlayerDetails = async (playerId: string): Promise => {
try {
const response = await axios.get(APIBASEURL/playerDetails/{playerId});
return response.data.response;
} catch (error: any) {
console.error('Get Player Details Error:', error);
throw error.response?.data?.error || 'Error fetching player details';
}
};
/*
Get recent matches for a specific player.
@param playerId - Unique identifier of the player.
@param limit - Number of recent matches to retrieve.
@returns Promise resolving to an array of Match objects.
*/
export const getPlayerMatches = async (playerId: string, limit: number = 5): Promise<Match[]> => {
try {
const response = await axios.get(APIBASEURL/playerMatches/{playerId}, {
params: { limit },
});
return response.data.matches;
} catch (error: any) {
console.error('Get Player Matches Error:', error);
throw error.response?.data?.error || 'Error fetching player matches';
}
};
// routes/playerRoutes.js
// Helper function to make API requests
const makeApiRequest = async (endpoint, params = {}) => {
try {
const response = await axios.get(baseURL/{endpoint}, { params });
console.log(API Response for endpointwithparams{JSON.stringify(params)}:, response.data);
return response.data;
} catch (error) {
if (error.response) {
console.error(
API Error: error.response.status−{JSON.stringify( error.response.data )}
);
throw new Error(
API Error: ${error.response.data.error || "Unknown error"}
);
} else if (error.request) {
console.error("No response received from API");
throw new Error("No response received from API");
} else {
console.error("Error setting up the request:", error.message);
throw new Error("Error setting up the request");
}
}
};
/**
Search for players by name directly using the new V1 API.
Returns up to 5 matching players.
*/
exports.searchPlayers = async (req, res) => {
const query = req.query.q;
if (!query) {
return res.status(400).json({ error: "Search query 'q' is required" });
}
try {
// Search in the local database first
const localPlayers = await Player.find({
name: { regex:query,options: "i" },
}).limit(5);
Get detailed information about a specific player by ID using the new V1 API.
*/
exports.getPlayerDetails = async (req, res) => {
const playerId = req.params.id;
if (!playerId) {
return res.status(400).json({ error: "Player ID is required" });
}
try {
// Check local DB first
const localPlayer = await Player.findOne({ player_id: playerId });
if (localPlayer) {
console.log(Player ID "${playerId}" found in local DB.);
return res.json({ status: "success", response: localPlayer });
}
console.log(
Player ID "${playerId}" not found in local DB. Fetching from API.
);
// If not found locally, fetch from API
const playerDetailsResponse = await makeApiRequest("lookupplayer.php", {
id: playerId,
});
// Validate response structure
if (
!playerDetailsResponse ||
playerDetailsResponse.players === null ||
!Array.isArray(playerDetailsResponse.players) ||
playerDetailsResponse.players.length === 0
) {
console.warn(API returned no data for Player ID "${playerId}".);
return res.status(404).json({ error: "Player not found" });
}
console.log(Fetched player details for Player ID "${playerId}" from API.);
// Save to local DB
try {
await Player.create(detailedPlayer);
console.log(Player ID "{playerId}" saved to local DB.);
} catch (err) {
if (err.code === 11000) {
console.warn(Player ID "{playerId}" already exists in the database.);
} else {
console.error("Error inserting player into DB:", err.message);
}
}
Get recent matches/events for a specific player using the new V1 API.
This example assumes that you have stored matches in your local DB.
*/
exports.getPlayerMatches = async (req, res) => {
const playerId = req.params.id;
const limit = parseInt(req.query.limit) || 5;
if (!playerId) {
return res.status(400).json({ error: "Player ID is required" });
}
try {
// Check if the player exists in the database
const player = await Player.findOne({ player_id: playerId });
if (!player) {
console.log(
Player ID "${playerId}" not found in local DB. Fetching player details to proceed.
);
// Attempt to fetch player details from API
const playerDetailsResponse = await makeApiRequest("lookupplayer.php", {
id: playerId,
});
// Validate response structure
if (
!playerDetailsResponse ||
playerDetailsResponse.players === null ||
!Array.isArray(playerDetailsResponse.players) ||
playerDetailsResponse.players.length === 0
) {
console.warn(API returned no data for Player ID "${playerId}".);
return res.status(404).json({ error: "Player not found" });
}
// Save to local DB
try {
await Player.create(detailedPlayer);
console.log(Player ID "{playerId}" saved to local DB.);
} catch (err) {
if (err.code === 11000) {
console.warn(
Player ID "{playerId}" already exists in the database.
);
} else {
console.error("Error inserting player into DB:", err.message);
}
}
} else {
console.log(Player ID "${playerId}" found in local DB.);
}
// Now that the player exists in the database, fetch matches
// Check local DB for matches
const localMatches = await Match.find({ player_id: playerId })
.sort({ date: -1 })
.limit(limit);
if (localMatches.length >= limit) {
console.log(
Found localMatches.lengthmatchesinlocalDBforPlayerID"{playerId}".
);
return res.json({
count: localMatches.length,
matches: localMatches,
});
}
console.log(
Found only localMatches.lengthmatchesinlocalDBforPlayerID"{playerId}". Fetching additional matches from API.
);
// Fetch player details to get the team ID
const playerDetailsResponse = await makeApiRequest("lookupplayer.php", {
id: playerId,
});
if (
!playerDetailsResponse ||
playerDetailsResponse.players === null ||
!Array.isArray(playerDetailsResponse.players) ||
playerDetailsResponse.players.length === 0
) {
throw new Error("Player not found");
}
if (!teamId) {
throw new Error("Team ID not available for this player");
}
// Fetch recent events for the team
const eventsResponse = await makeApiRequest("eventslast.php", {
id: teamId,
});
if (
!eventsResponse ||
!eventsResponse.results ||
!Array.isArray(eventsResponse.results)
) {
throw new Error("No events found for the player's team");
}
// Save new matches to local DB
await Match.insertMany(
matches,
{ ordered: false } // Continue on duplicate errors
).catch((err) => {
if (err.code === 11000) {
console.warn("Duplicate match entries detected.");
} else {
console.error("Error inserting matches into DB:", err.message);
}
});
// Combine local and newly fetched matches
const combinedMatches = [...localMatches, ...matches].slice(0, limit);
Now what is going on is that I am not able to search player
'use client'
import { useState } from 'react'
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
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'
// Mock API function
const fetchData = async (endpoint) => {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 500))
// Return mock data based on endpoint
switch (endpoint) {
case 'liveScore':
return { homeTeam: "Team A", awayTeam: "Team B", homeScore: 2, awayScore: 1 }
case 'leagues':
return ['Premier League', 'La Liga', 'Bundesliga', 'Serie A', 'Ligue 1', 'Champions League', 'Europa League']
case 'news':
return [
{ id: 1, title: "Breaking: Star Player Injured", content: "Team A's star player out for 3 weeks..." },
{ id: 2, title: "Transfer Rumors: Who's Moving Where?", content: "Latest transfer gossip from around the league..." },
]
case 'players':
return [
{ id: 1, name: "Lionel Messi", team: "Inter Miami", position: "Forward" },
{ id: 2, name: "Cristiano Ronaldo", team: "Al Nassr", position: "Forward" },
]
case 'teams':
return [
{ id: 1, name: "Manchester United", league: "Premier League", history: "Founded in 1878, 20 league titles..." },
{ id: 2, name: "Real Madrid", league: "La Liga", history: "Founded in 1902, 34 La Liga titles..." },
]
default:
return []
}
}
export default function FootballDashboard() {
const [activeTab, setActiveTab] = useState('liveScore')
return (
FootballBuzz
Live Score Leagues News Players Teams Fantasy Videos
So basically when the user clicks on an image, I am displaying the details of the image as a modal/dialog box. But after the dialog box is closed, the screen scroll freezes. Things work on the screen, but I cant scroll down and access the other elements. Any idea how i can debug.
I feel its because somehow the modal is disabling my scroll bar.
Below is my dialog box code
import React from 'react'
import { Dialog, Transition } from '@headlessui/react'
import { Fragment } from 'react'
import {XIcon} from '@heroicons/react/solid'
import {useRecoilState} from 'recoil'
import {openState} from '../../../atoms/modalAtom'
It sounds like you're encountering issues with the modal's scroll functionality and overall layout. This is a common challenge when working with modals, especially when integrating multiple components and state management libraries like Recoil. Below, I’ll provide a comprehensive approach to resolving the scrolling issue and enhancing the modal's appearance.
1. Ensure Proper Modal Structure and Styling
To make the modal scrollable and visually appealing, it's crucial to structure it correctly and apply appropriate Tailwind CSS classes. Here's a refined version of your PlayerModal.tsx component with enhanced styling and scrolling capabilities:
max-h-[90vh] overflow-y-auto: Ensures the modal doesn't exceed 90% of the viewport height and allows vertical scrolling if content overflows.
Enhanced Layout:
Structured Information: Organized player details in a clear and readable format using Tailwind's grid and spacing utilities.
Responsive Avatar and Text: Properly sized avatar and aligned text for better aesthetics.
Improved Error Handling:
Display a user-friendly error message if data fetching fails.
Accessibility Enhancements:
DialogClose: Positioned the close button appropriately and made sure it's accessible.
2. Managing Body Scroll Lock Correctly
One of the common reasons for scroll issues after closing a modal is improper handling of the overflow property on the <body> element. Ensure that your modal library or custom Dialog component correctly manages this. Here's how you can handle it manually if needed:
// Inside PlayerModal.tsx
import useBodyScrollLock from '../utils/useBodyScrollLock';
// Inside the component
useBodyScrollLock(isOpen);
3. Ensure Single Modal Rendering
Having multiple instances or different modal libraries can cause conflicts that affect scroll behavior. Ensure that:
Only One Modal Instance is Active at a Time: Avoid rendering multiple modals simultaneously.
Consistent Modal Library: Stick to one modal implementation (e.g., @headlessui/react) to prevent conflicts.
4. Verify Global CSS and Parent Containers
Sometimes, parent containers or global CSS rules can interfere with scrolling. Ensure that:
No Parent Element is Restricting Height or Overflow: Check parent divs for overflow-hidden, fixed heights, or other CSS properties that might restrict scrolling.
Tailwind Configuration: Verify that your Tailwind setup doesn't have conflicting styles.
5. Debugging Steps Using Developer Tools
To pinpoint the issue, use your browser's developer tools:
Check <body> Overflow:
Open DevTools (F12 or right-click > Inspect).
Select the <body> element and inspect the overflow property in the Styles panel.
Ensure that after closing the modal, overflow is not set to hidden.
Inspect Modal Structure:
Ensure that the modal's container has appropriate classes for scrolling (overflow-y-auto).
Verify that no unexpected CSS rules are applied that might restrict scrolling.
Look for JavaScript Errors:
Check the Console tab for any errors that might interfere with modal behavior.
6. Enhance the Overall UI for Better Appearance
To make the modal more visually appealing, consider the following enhancements:
Animations:
Utilize smooth transitions for opening and closing the modal.
Tailwind CSS provides utilities like transition, ease-out, and duration-300 for this purpose.
Responsive Design:
Ensure the modal looks good on various screen sizes.
Use responsive classes like md:max-w-2xl and lg:max-w-4xl.
Typography and Spacing:
Use consistent font sizes and weights.
Apply adequate padding and margins for a clean layout.
Here's an example of adding transitions and responsive design:
Proven Reliability: It's a well-maintained library that handles accessibility and scroll locking out of the box.
Simplified Codebase: Reduces the need for custom scroll management logic.
Ease of Customization: Easily apply Tailwind classes for styling.
8. Final Recommendations
Consistent State Management: Ensure that only one state (either Recoil or React's useState) manages the modal's open/close state to prevent conflicts.
Avoid Nesting Modals: Ensure that modals aren't nested within other components that might interfere with their behavior.
Test Across Devices: Verify the modal's functionality and appearance on different screen sizes and devices to ensure responsiveness.
By implementing these suggestions, your modal should handle scrolling correctly, and its appearance should be significantly improved. If issues persist, consider isolating the modal component in a simpler setup to identify any external factors causing the problem.