Refactor Pokémon data fetching and validation logic; improve error handling and logging

This commit is contained in:
vista-man
2025-03-26 10:25:08 +01:00
parent 6e06965bc0
commit 5b4fcda9d6
4 changed files with 202 additions and 14 deletions

BIN
v2/assets/pokeball.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

189
v2/error_log.txt Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,11 +1,11 @@
let currentPokemonId = null;
document.addEventListener("DOMContentLoaded", () => {
const MAX_POKEMONS = 151;
const pokemonID = new URLSearchParams(window.location.search).get("id");
const id = parseInt(pokemonID, 10);
if (id < 1 || id > MAX_POKEMONS) {
if (isNaN(id) || id < 1) {
console.error(`Invalid Pokémon ID: ${id}`);
return (window.location.href = "./index.html");
}
@@ -15,6 +15,7 @@ document.addEventListener("DOMContentLoaded", () => {
async function loadPokemon(id) {
try {
console.log(`Loading data for Pokémon ID ${id}...`);
const pokemon = await fetch(`./get-pokemon.php?id=${id}`).then((res) =>
res.json()
);
@@ -39,16 +40,12 @@ async function loadPokemon(id) {
leftArrow.removeEventListener("click", navigatePokemon);
rightArrow.removeEventListener("click", navigatePokemon);
if (id !== 1) {
leftArrow.addEventListener("click", () => {
navigatePokemon(id - 1);
});
}
if (id !== 151) {
rightArrow.addEventListener("click", () => {
navigatePokemon(id + 1);
});
}
window.history.pushState({}, "", `./detail.html?id=${id}`);
}

View File

@@ -28,8 +28,10 @@ document.addEventListener("DOMContentLoaded", () => {
function fetchPokemons() {
console.log("Fetching Pokémon data from server...");
fetch(`./get-pokemon.php`)
.then((response) => response.json())
.then((data) => {
.then((response) => response.text())
.then((text) => {
console.log("Server response:", text);
const data = JSON.parse(text);
if (Array.isArray(data)) {
allPokemons = data;
localStorage.setItem("pokemons", JSON.stringify(allPokemons));