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
{/* Removed fetchData prop */} ) } This is FootballDashboard.tsx Now Problem is that on clicking photo+name it is showing me player but when screen opens there's no option of scrolling so I think problem is with frontend because backend is working fine photo is half cut one details screen Can you please solve it make it scrollable and make it beutifull A similar topic I found on stackoverflow 2
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'
export default Design
I think its the scrollbar. Any leads on how i can debug?
javascriptreactjsnext.jstailwind-csstailwind-ui
Share
Edit
Follow
asked Jul 10, 2022 at 21:40
rohit's user avatar
rohit
17922 silver badges1515 bronze badges
Add a comment
1 Answer
Sorted by:
Highest score (default)
2
I had the same issue where after closing the modal, scrolling stopped working on the main page.
Problem: I was rendering a list where each item had a button to open up the modal, and I had put the modal inside that list.
const [isOpen, setIsOpen] = useState(false);
const data = [
// My data was an array of objects,
// where each object contained position data
]
const closeModal = () => {
setIsOpen(false);
};
const openModal = () => {
setIsOpen(true);
};
{data.map((position) => ( Open Modal // <--------- Problem! ))}
Solution: Move the modal out of the list and create a state variable that gets updated in the openModal and closeModal functions:
const [selectedPosition, setSelectedPosition] = useState(null);
const [isOpen, setIsOpen] = useState(false);
const data = [
// My data was an array of objects,
// where each object contained position data
]
{data.map((position) => ( openModal(position)}>Open Modal ))} // <-------- Solved!
I'm using shadcn UI with next js don't change any config
The issue you're encountering—where the modal opens correctly but prevents the main page from scrolling after closing, and the modal content (like the player photo) is partially cut off—is likely due to a combination of state management and CSS configuration in your modal implementation. Let's address both problems step-by-step to ensure a smooth and visually appealing user experience.
1. Fixing the Modal Scroll Lock Issue
Problem:
After closing the modal, the main page remains unscrollable. This behavior is typically caused by the modal component inadvertently leaving the overflow: hidden style on the <body>, preventing any further scrolling.
Solution:
Ensure that the modal component correctly manages the overflow property on the <body>. Additionally, verify that the modal is properly unmounted and that any side-effects (like overflow changes) are cleaned up when the modal closes.
2. Ensuring Modal Content is Scrollable and Visually Appealing
Problem:
The player photo within the modal is half-cut, and the modal doesn't allow scrolling, making it inaccessible or visually incomplete.
Solution:
Configure the modal's content to be scrollable if it exceeds the viewport height. This can be achieved by setting appropriate CSS classes to manage the overflow within the modal. Also, ensure that the modal's layout is responsive and aesthetically pleasing across different screen sizes.
Step-by-Step Implementation
Let's revise your PlayerModal.tsx to address both issues:
a. Correct the TypeScript Typing
Ensure that your PlayerModal component correctly types its props. This is crucial for React to pass the props as expected.
TypeScript Typing: Changed the component declaration to React.FC<PlayerModalProps> to ensure proper type checking of props.
Dialog Configuration:
Utilized the open prop and the onOpenChange callback to manage the modal's open state correctly.
Added max-h-[90vh] overflow-y-auto to DialogContent to make the modal content scrollable if it exceeds 90% of the viewport height.
Improved Content Layout: Structured the modal content with appropriate spacing (space-y-4, flex, etc.) and ensured responsive and accessible design.
Error Handling: Enhanced error messaging to display a user-friendly error if fetching data fails.
b. Ensure Proper Modal Usage in PlayerSearch.tsx
Make sure that the PlayerModal is correctly integrated within your PlayerSearch component and that it's not nested within elements that might interfere with its behavior.
tsx
Key Changes:
Modal Placement: Ensured that PlayerModal is rendered outside the list of player cards to prevent any nesting issues that might affect scroll behavior.
Enhanced Layout: Improved the grid layout for better responsiveness and visual appeal.
Error Messaging: Updated error handling to display more descriptive messages.
c. Adjust Global CSS if Necessary
Ensure that no global CSS is inadvertently restricting the scroll behavior. For instance, check your global styles (like globals.css) to ensure that the <body> or other parent elements do not have styles that prevent scrolling.
css
/* globals.css */
/* Ensure the body can scroll when no modal is open */
body {
overflow: auto;
}
/* Optionally, you can add transitions for smooth scrolling */
d. Verify Modal Unmounting and State Reset
Ensure that when the modal closes, it correctly resets its state and unmounts to allow the main page to regain its scroll functionality.
For example, in PlayerModal.tsx, make sure the onClose function properly updates the parent component's state:
This ensures that when the modal requests to close (e.g., when clicking outside or pressing the escape key), the onClose callback is invoked, updating isModalOpen in PlayerSearch.tsx and allowing the page to scroll again.
e. Test the Implementation
After making these changes:
Run Your Application: Start your development server and navigate to the player search component.
Perform a Search: Enter a player name and execute the search to populate the list of players.
Open the Modal: Click on a player's photo or name to open the modal. Verify that:
The modal opens correctly.
The content within the modal is fully visible or scrollable if it exceeds the viewport.
The main page scroll is disabled only when the modal is open.
Close the Modal: Close the modal by clicking the close button or outside the modal area. Verify that:
The modal closes smoothly.
The main page becomes scrollable again.
There are no lingering styles preventing scroll.
Additional Recommendations
Accessibility: Ensure that your modal is accessible. Utilize ARIA attributes and focus management to enhance usability for all users.
Responsive Design: Test the modal across various screen sizes to ensure that it remains user-friendly on mobile devices, tablets, and desktops.
Performance: Optimize image loading within the modal to prevent delays or layout shifts. Consider using lazy loading or placeholders for images.
Error Boundaries: Implement error boundaries to catch and handle unexpected errors gracefully, enhancing the robustness of your application.
By following these steps and adjustments, your modal should function correctly without freezing the main page's scroll, and the modal content should be fully accessible and visually appealing.