-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThirdPartyAPI.js
70 lines (55 loc) · 3.02 KB
/
ThirdPartyAPI.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// This function makes the output for the location names a little more readable and pretty
function formatLocationName(locationName) {
return locationName.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
async function fetchPokemonData() {
try {
const pokemonName = document.getElementById("pokemonName").value.toLowerCase();
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`);
// capitalizedPokeName allows for future reference to name entry
let capitalizedPokeName = pokemonName.charAt(0).toUpperCase() + pokemonName.slice(1);
// Using this portion of code to catch any input errors
if (!response.ok) {
const infoContainer = document.getElementById("infoContainer");
infoContainer.innerHTML = `<p>No results can be found for ${capitalizedPokeName}. Please try again.</p>`;
return; // Exit the function early if there's an error
}
// Used to catch blank entries
if (capitalizedPokeName.length === 0) {
const infoContainer = document.getElementById("infoContainer");
infoContainer.innerHTML = "<p>Please enter a Pokemon to be located.</p>";
return; // Exit the function early if the input is blank
}
const data = await response.json();
const pokemonSprite = data.sprites.front_default;
// Show image container
const imageContainer = document.getElementById("imageContainer");
imageContainer.style.display = "block";
const imageElement = document.getElementById("pokemonSprite");
imageElement.src = pokemonSprite;
const infoContainer = document.getElementById("infoContainer");
infoContainer.innerHTML = "";
// Pokemon Location call
const pokeLocation = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}/encounters`);
if (!pokeLocation.ok) {
throw new Error("Could not fetch Pokemon Location resource data.");
}
// Extracting in-game location of where to find Pokemon in question
let locationInfo;
const locationData = await pokeLocation.json();
if (!locationData[0]) { // Check to see if locationData[0] is falsy or undefined
locationInfo = `${pokemonName} Encounter Location: ???`;
} else {
const locationOutput = formatLocationName(locationData[0].location_area.name);
capitalizedPokeName = pokemonName.charAt(0).toUpperCase() + pokemonName.slice(1);
locationInfo = `${capitalizedPokeName} Encounter Location: ${locationOutput}`;
}
const locationOutputElement = document.createElement("p");
locationOutputElement.innerHTML = locationInfo;
infoContainer.appendChild(locationOutputElement);
} catch (error) {
console.error("ERROR OCCURRED: ", error);
}
}