// Sort leagues based on the defined order
const sortedLeagues = leagueOrder.filter(league => Object.keys(filteredScores).includes(league))
.concat(Object.keys(filteredScores).filter(league => !leagueOrder.includes(league)))
// Map competition IDs to league names
const leagueIds = {
2014: "La Liga",
2021: "Premier League",
2002: "Bundesliga",
2019: "Serie A",
2015: "Ligue 1",
2001: "UEFA Champions League",
2146: "UEFA Europa League",
// Add more mappings as needed
};
// Transform and filter matches
const filteredMatches = response.data.matches.map((match) => ({
id: match.id,
utcDate: match.utcDate,
status: match.status,
league: leagueIds[match.competition.id] || "Other",
homeTeam: match.homeTeam,
awayTeam: match.awayTeam,
score: match.score,
odds: Math.random().toFixed(2), // Placeholder for odds
avgP: (Math.random() * 100).toFixed(2), // Placeholder for average probability
avgG: (Math.random() * 5).toFixed(2), // Placeholder for average goals
cG: Math.floor(Math.random() * 10), // Placeholder for custom metric
BTS: Math.random() > 0.5 ? "Yes" : "No", // Both Teams to Score
FTS: Math.random() > 0.5 ? "Yes" : "No", // First Team to Score
cAG: Math.random() > 0.5 ? "Yes" : "No", // Custom metric
}));
return filteredMatches;
} catch (error) {
logger.error("Error fetching scores from API:", error.message);
throw new Error("Failed to fetch scores from external API.");
}
};
/**
Store scores in the MongoDB database.
@param {Array} scores - Array of score objects to store.
*/
const storeScoresInDB = async (scores) => {
try {
if (scores.length === 0) return;
// Insert many with ordered:false to continue on duplicate errors
await Score.insertMany(scores, { ordered: false });
logger.info(Inserted ${scores.length} scores into the database.);
} catch (err) {
if (err.code === 11000) {
logger.warn("Duplicate score entries detected. Skipping duplicates.");
} else {
logger.error("Error inserting scores into DB:", err.message);
throw new Error("Failed to store scores in the database.");
}
}
};
/**
Fetch scores from the database.
@returns {Promise} Array of score documents.
*/
const getScoresFromDB = async () => {
try {
const scores = await Score.find({})
.sort({ utcDate: -1 }) // Sort by latest date
.limit(100) // Limit to latest 100 matches
.lean(); // Returns plain JavaScript objects
return scores;
} catch (error) {
logger.error("Error fetching scores from DB:", error.message);
throw new Error("Failed to retrieve scores from the database.");
}
};
Controller to handle fetching and serving live scores.
Endpoint: GET /api/scores
*/
const scoresController = async (req, res) => {
try {
// Check if live scores are cached
const cachedScores = cache.get("liveScores");
if (cachedScores) {
logger.info("Serving cached live scores.");
return res.status(200).json(cachedScores);
}
// Fetch scores from the database
let scores = await getScoresFromDB();
if (scores.length === 0) {
logger.info("No scores found in DB. Fetching from external API.");
// Fetch scores from external API
scores = await fetchScoresFromAPI();
// Store fetched scores in the database
await storeScoresInDB(scores);
}
// Group scores by league
const groupedMatches = groupMatchesByLeague(scores);
// Cache the grouped matches with TTL of 5 minutes (300 seconds)
cache.set("liveScores", groupedMatches, 300);
logger.info("Cached live scores.");
// Serve the grouped matches
res.status(200).json(groupedMatches);
} catch (error) {
logger.error("Error in scoresController:", error.message);
res.status(500).json({
message: "Unable to retrieve live scores. Please try again later.",
error: error.message,
});
}
};
indicates that match.score is undefined when your component tries to access match.score.fullTime.home and match.score.fullTime.away. This results in a TypeError because you're attempting to read properties of undefined.
To resolve this issue, you'll need to implement defensive programming practices in your frontend code to handle cases where match.score might be undefined. Additionally, ensuring that your backend provides consistent and complete data can help mitigate such issues.
Here's a step-by-step guide to troubleshoot and fix the problem:
1. Understanding the Error
In your FootballDashboard.tsx (specifically at line 66), you have:
This line assumes that match.score and match.score.fullTime are always defined. However, if for any match, the score is undefined or fullTime is missing, accessing home or away will throw a TypeError.
2. Implement Defensive Checks in the Frontend
To prevent the error, modify your code to safely access the score object using optional chaining (?.). This ensures that if score or fullTime is undefined, the expression gracefully falls back to the default value ('-').
Optional Chaining (?.): This operator allows you to safely access nested object properties. If any part of the chain is undefined or null, the entire expression short-circuits and returns undefined.
Nullish Coalescing (??): This operator returns the right-hand side operand when the left-hand side is null or undefined. It's ideal for providing default values.
By updating the code as shown, your component will now display '-' instead of throwing an error when match.score or match.score.fullTime is undefined.
3. Review and Update Other Instances
Ensure that any other parts of your code that access match.score or its nested properties also implement similar safety checks. For example, in your LiveScore component, verify that all accesses to match.score.fullTime are guarded.
While defensive programming on the frontend is essential, ensuring that your backend consistently provides complete data is equally important. Here's how you can enhance your backend controller to ensure that score is always defined:
Review the fetchScoresFromAPI Function:
Ensure that every match object returned by fetchScoresFromAPI includes a score property. Given your current implementation, it seems you're mapping match.score directly from the external API. However, some matches (e.g., not started yet) might have score as null.
Default score Object: If match.score is null or undefined, assign a default object with fullTime and halfTime properties set to null. This ensures that the frontend always has a score object to work with, preventing unexpected undefined values.
5. Implement TypeScript Interfaces (Optional but Recommended)
Using TypeScript interfaces can help catch such issues during development by enforcing type checks.
Type Safety: Ensures that all required properties are present and have the correct types.
Development Experience: Provides better tooling support, such as IntelliSense and error highlighting.
Maintainability: Makes the codebase easier to understand and maintain.
6. Final Adjustments and Testing
After implementing the above changes:
Restart Your Development Server: Ensure that all changes are properly loaded.
Clear Cache and Test: Sometimes, stale cache can cause issues. Clear your browser's cache and test the application to ensure the error is resolved.
Monitor Logs: Keep an eye on both frontend and backend logs to catch any other potential issues.
Handle Edge Cases: Consider other scenarios where data might be missing or malformed and handle them gracefully.
7. Summary of Changes
Frontend (FootballDashboard.tsx and LiveScore components):
Use optional chaining (?.) when accessing nested properties.
Provide default values using nullish coalescing (??) to handle null or undefined cases.
Backend (scoresController.js):
Ensure that the score property is always defined, even if it's empty.
Implement thorough error handling and logging to catch and debug issues promptly.
TypeScript Interfaces (Optional):
Define clear interfaces for your data models to leverage TypeScript's type-checking capabilities.
By following these steps, you should be able to resolve the runtime error and ensure that your application handles missing or incomplete data gracefully.
Example of Updated Frontend Code with Defensive Programming:
After making these changes, thoroughly test your application to ensure that:
The error no longer occurs.
Matches without scores display '-' appropriately.
Other functionalities are unaffected.
The UI remains consistent and user-friendly.
If you continue to experience issues, consider adding logging or further debugging to identify specific matches or data inconsistencies causing the problem.