Your PlayerSearch component is well-structured and leverages React hooks effectively to manage state and handle user interactions. Below are some suggestions and best practices to enhance the component's functionality, performance, and accessibility:
1. Use onKeyDown Instead of onKeyPress
The onKeyPress event is deprecated in React. It's recommended to use onKeyDown or onKeyUp instead.
Change:
<Input
// ...other props
onKeyDown={handleKeyDown}
/>
Implementation:
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
handleSearch();
}
};
2. Improve Error Handling
Currently, the catch block captures any error and displays it directly using toast.error(error). It's better to extract a meaningful message from the error object to provide a clearer message to the user.
Change:
} catch (error: any) {
const errorMessage = error?.response?.data?.message || error.message || 'An unexpected error occurred.';
toast.error(errorMessage);
}
3. Enhance Accessibility
Ensure that interactive elements are accessible via keyboard and have appropriate ARIA roles.
Player Item:
Instead of using a div with onClick, use a button or add role="button" and tabIndex={0} to make it accessible.
Change:
<button
key={player.player_id}
className="flex items-center p-4 bg-white rounded shadow hover:bg-gray-100 cursor-pointer w-full text-left"
onClick={() => handlePlayerClick(player.player_id)}
>
{/* Avatar and Player Info */}
</button>
4. Memoize Handlers to Prevent Unnecessary Re-renders
Use useCallback to memoize functions like handleSearch, handlePlayerClick, and handleKeyDown to prevent unnecessary re-renders, especially if the component grows in complexity.
import { useState, useCallback } from 'react';
// ...
const handleSearch = useCallback(async () => {
// existing implementation
}, [searchTerm]);
const handlePlayerClick = useCallback((playerId: string) => {
setSelectedPlayerId(playerId);
setIsModalOpen(true);
}, []);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
handleSearch();
}
}, [handleSearch]);
5. Debounce Search Input (Optional)
If you plan to extend the search functionality to support live searching (e.g., searching as the user types), implementing a debounce mechanism would prevent excessive API calls.
However, since your current implementation triggers search on button click or pressing "Enter," this might not be necessary right now.
6. Loading State Enhancement
While you have a loading state, consider disabling the input field during loading to prevent multiple submissions.
Change:
<Input
// ...other props
disabled={loading}
/>
7. Type Safety for Errors
Instead of using any for the error type, you can define a more specific type or use TypeScript's type guards to ensure type safety.
Example:
} catch (error: unknown) {
let errorMessage = 'An unexpected error occurred.';
if (error instanceof Error) {
errorMessage = error.message;
} else if (typeof error === 'string') {
errorMessage = error;
}
toast.error(errorMessage);
}
8. Optimizing Re-renders for Player List
If the player list becomes large, consider using virtualization libraries like react-window or react-virtualized to optimize rendering performance.
9. Styling Enhancements
Ensure that the component is responsive and visually consistent across different devices. You might also want to add hover and focus states for better user experience.
10. Example of the Updated Component
Here's an updated version of your component incorporating the suggestions:
'use client';
import { useState, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import PlayerModal from './PlayerModal';
import { Player } from '../types';
import { searchPlayers } from '../utils/api';
import { toast } from 'react-toastify';
const PlayerSearch: React.FC = () => {
const [searchTerm, setSearchTerm] = useState<string>('');
const [players, setPlayers] = useState<Player[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [selectedPlayerId, setSelectedPlayerId] = useState<string | null>(null);
const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
const handleSearch = useCallback(async () => {
if (!searchTerm.trim()) {
toast.error("Please enter a search term.");
setPlayers([]);
return;
}
setLoading(true);
setPlayers([]);
try {
const data = await searchPlayers(searchTerm);
setPlayers(data);
if (data.length === 0) {
toast.info("No players found. Try a different search.");
}
} catch (error: unknown) {
let errorMessage = 'An unexpected error occurred.';
if (error instanceof Error) {
errorMessage = error.message;
} else if (typeof error === 'string') {
errorMessage = error;
}
toast.error(errorMessage);
} finally {
setLoading(false);
}
}, [searchTerm]);
const handlePlayerClick = useCallback((playerId: string) => {
setSelectedPlayerId(playerId);
setIsModalOpen(true);
}, []);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
handleSearch();
}
}, [handleSearch]);
return (
<div>
<Card>
<CardHeader>
<CardTitle>Player Search</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col md:flex-row gap-2 mb-4">
<Input
type="text"
placeholder="Search players..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyDown={handleKeyDown}
disabled={loading}
aria-label="Search players"
/>
<Button onClick={handleSearch} disabled={loading}>
{loading ? 'Searching...' : 'Search'}
</Button>
</div>
<div className="space-y-4">
{loading ? (
<p>Searching...</p>
) : (
players.map(player => (
<button
key={player.player_id}
className="flex items-center p-4 bg-white rounded shadow hover:bg-gray-100 cursor-pointer w-full text-left"
onClick={() => handlePlayerClick(player.player_id)}
aria-label={`View details for ${player.name}`}
>
<Avatar className="mr-4">
{player.photo_url ? (
<img src={player.photo_url} alt={player.name} />
) : (
<AvatarFallback>
{player.name.charAt(0)}
</AvatarFallback>
)}
</Avatar>
<div>
<h3 className="text-lg font-semibold">{player.name}</h3>
<p className="text-sm text-gray-500">{player.position} - {player.team}</p>
</div>
</button>
))
)}
</div>
</CardContent>
</Card>
{/* Player Modal */}
{selectedPlayerId && (
<PlayerModal
playerId={selectedPlayerId}
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
/>
)}
</div>
);
};
export default PlayerSearch;
11. Additional Recommendations
-
Unit Testing: Implement unit tests using frameworks like Jest and React Testing Library to ensure your component behaves as expected.
-
Prop Types Validation: Although you're using TypeScript, ensure that the types for props and states are accurately defined to prevent runtime errors.
-
Error Boundary: Consider wrapping your component or higher-level components with an Error Boundary to catch and handle unexpected errors gracefully.
By incorporating these improvements, your PlayerSearch component will not only be more robust and maintainable but also provide a better user experience.