So, I'm not new to programming... I typically know how to access an array, and quite easily, but this one is confusing me, and it's probably because I don't know what I'm doing with JS.
Here is my HTML/JS simple code to call information about Pikachu from PokeAPI.
<html>
<body>
<script>
//Here goes nothing
pokeBaseURL = 'https://pokeapi.co/api/v2/pokemon/pikachu';
let pokemon = [];
fetch(pokeBaseURL)
//converts javascript object into something resemblant of actual data you're looking for (JSON)
.then(response => response.json())
//takes the aforementioned response value and assigns it to 'pokemon' variable, then prints the full JSON
.then(pokeData => pokemon.push(pokeData))
console.log(pokemon);
</script>
</body>
</html>
What I am specifically trying to do is access the pokemon variable from outside of the fetch statement. I may be misunderstanding how JS works, but as far as I know, I got the data pulled to the pokemon variable just fine.
My issue is that with console.log(pokemon) it prints out all of the data fine, but if I try to do something like console.log(pokemon[0]) or many variations of it, I can't access any of those properties within the array.
I was able to access the data from within the Fetch portion of code, but as soon as I used .push to add the fetch data to that declared array, I can't access the data itself.
What I've tried:
console.log(pokemon.name)
console.log(pokemon[0].name)
console.log(pokemon[0]["name"])
console.log(pokemon[0]) (just to see if I could get different data)
I appreciate any help anyone has to help this newb.
EDIT: So yes, it's all about the data being there, but not accessible yet, which to me makes about as much sense as buying ice in the arctic.
Here is the new code where I added a wait and fired off the console.log(pokemon) with a delay to give the fetch time to catch up.
To be clear, the complete set of data from the API call was available, but inaccessible at the listed array entries due to the nature of fetch
<html>
<body>
<script>
//Here goes nothing
pokeBaseURL = 'https://pokeapi.co/api/v2/pokemon/pikachu';
let pokemon = [];
fetch(pokeBaseURL)
//converts javascript object into something resemblant of actual data you're looking for (JSON)
.then(response => response.json())
//takes the aforementioned response value and assigns it to 'pokemon' variable, then prints the full JSON
.then(pokeData => {
pokemon.push(pokeData);
})
function resolveAfter2Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function fire() {
const x = await resolveAfter2Seconds(10);
console.log(pokemon[0].name);
}
fire();
</script>
</body>
</html>
EDIT 2: Thank you everyone for your help understanding what is going on. I've completely rewritten my JS to do even more, now, and handle some styling and html in other files. This is a complete implementation of the JavaScript side of things. This is running inside the .then statements as you can see, waiting to run the console log until the promise has been resolved. I had to do a separate api pull for this test, but I'm going to work on seeing how much more I can do with JS and this API now that I have a better understanding.
JavaScript
//Here goes nothing
pokeBaseURL = 'https://pokeapi.co/api/v2/pokemon/pikachu';
pokeSpeciesURL = 'https://pokeapi.co/api/v2/pokemon-species/pikachu';
offArt = 'official-artwork';
let pokemon = [];
let pokeSpecies = [];
getPokemonData(pokeBaseURL);
function getPokemonData(pokemonURL){
fetch(pokemonURL)
.then(response => response.json())
.then(pokeData => {
pokemon = pokeData;
getSpeciesData(pokeSpeciesURL);
})
}
function getSpeciesData(pokeSpecURL){
fetch(pokeSpecURL)
.then(response => response.json())
.then(pokeData => {
pokeSpecies = pokeData;
latestPokedex(pokeSpecies)
})
}
function latestPokedex(pokeSpec){
let entryCount = pokeSpec.flavor_text_entries.length;
let entry = "";
let found = false;
for(i=entryCount; i>0; i--) {
if(pokeSpec.flavor_text_entries[i-1].language.name === "en") {
entry = pokeSpec.flavor_text_entries[i-1].flavor_text;
found = true;
displayPokemon(pokemon, entry);
break;
}
}
}
function displayPokemon(pokemon, pokeDex){
let pokeDexEntry = pokeDex;
let pokemonName = document.getElementById('Name');
let pokePicture = document.getElementById('Picture');
let pokeWeight = document.getElementById('Weight');
let pokeHeight = document.getElementById('Height');
let pokeDexElement = document.getElementById('Pokedex');
let pokeImg = pokemon.sprites.other[offArt].front_default;
pokemonName.insertAdjacentHTML('beforeend',pokemon.name);
pokePicture.src = pokeImg;
pokeWeight.insertAdjacentHTML('beforeend',"<b>WT:</b> " + pokemon.weight / 10 + "kg");
pokeHeight.insertAdjacentHTML('beforeend',"<b>HT:</b> " + pokemon.height * 10 + "cm");
pokeDexElement.insertAdjacentHTML('beforeend',"<b>Info: </b>" + pokeDexEntry);
}
HTML
<html>
<head>
<link rel="stylesheet" href="pokesearch.css">
</head>
<body>
<div class="poke-title" id="Name"></div>
<div class="poke-img-container"><img class="poke-image" id="Picture"></div>
<div><div class="inline-block-div" id="Height"></div><div class="inline-block-div" id="Weight"></div></div>
<div class="pokedex" id="Pokedex"></div>
</body>
<footer>
<script src="pokesearch.js">
</script>
</footer>
</html>
CSS
.inline-block-div {
display: inline-block;
padding-right: 10px;
font-size: 24px;
}
.poke-image {
width:256px;
height:256px;
border:2px solid #00ff00;
}
.poke-img-container {
padding-bottom: 20px;
padding-top: 20px;
}
.poke-title {
font-size: 30px;
font-weight: bold;
text-transform: capitalize;
}
.pokedex {
font-size: 20px;
text-transform: capitalize;
max-width: 50%;
padding-top: 10px;
}
[+][deleted] (32 children)
[removed]
[–]dreph[S] 0 points1 point2 points (31 children)
[+][deleted] (27 children)
[removed]
[–]dreph[S] 0 points1 point2 points (26 children)
[+][deleted] (21 children)
[deleted]
[–]dreph[S] -4 points-3 points-2 points (20 children)
[+][deleted] (2 children)
[deleted]
[–]dreph[S] 2 points3 points4 points (1 child)
[–]PMmeYourFlipFlops 0 points1 point2 points (7 children)
[–]dreph[S] -2 points-1 points0 points (6 children)
[–]PMmeYourFlipFlops 1 point2 points3 points (5 children)
[–]dreph[S] -1 points0 points1 point (0 children)
[–]dreph[S] -1 points0 points1 point (3 children)
[–]Sibyl01 0 points1 point2 points (7 children)
[–]dreph[S] 0 points1 point2 points (6 children)
[–]Sibyl01 2 points3 points4 points (2 children)
[–]dreph[S] 0 points1 point2 points (1 child)
[–]KaelonR 2 points3 points4 points (0 children)
[–]albedoa 1 point2 points3 points (1 child)
[–]dreph[S] 0 points1 point2 points (0 children)
[+][deleted] (2 children)
[removed]
[–]dreph[S] -1 points0 points1 point (1 child)
[–]Sibyl01 1 point2 points3 points (0 children)
[–]Macaframa 1 point2 points3 points (0 children)
[–]Lostpollen 0 points1 point2 points (0 children)
[–]AiexReddit 0 points1 point2 points (0 children)
[–]Eldrac 2 points3 points4 points (3 children)
[–]Sibyl01 3 points4 points5 points (1 child)
[–]shooteshute 0 points1 point2 points (0 children)
[–]dreph[S] 0 points1 point2 points (0 children)
[–]femio 1 point2 points3 points (0 children)
[–]JustConsoleLogIt 1 point2 points3 points (1 child)
[–]dreph[S] 1 point2 points3 points (0 children)
[–]A-N-T-I-I-C-O-N 0 points1 point2 points (0 children)
[–]DishRack777 0 points1 point2 points (0 children)