Json Array empty

Viewed 48

passed Json to array and console show empty but with objects inside. but when printing with index console.log show undefind.. whats wrong ?

let pokeName = [];
let pokeId = [];
let pokeImg = [];
let pokeType = [];
let pokeMove = [];

for (let i=1; i< 21; i++) {
    fetch(`https://pokeapi.co/api/v2/pokemon/${i}/`)
        .then(Response => Response.json())
        .then(data => {
            pokeId.push(data['id']);
            pokeName.push(data['name']);

            const dataTypes = data['types'];
            pokeType.push(dataTypes[0]['type']['name']);

            const dataMoves = data['moves'];
            pokeMove.push(dataMoves[0]['move']['name']);

            pokeImg.push(data['sprites']['front_default']);
        });
}


console.log(pokeName);
console.log(pokeId);
console.log(pokeImg);
console.log(pokeMove);
console.log(pokeType);
3 Answers

Your console logs are running before your fetch calls are finishing. You can use async/await to solve the issue.

Something like this should work:

let pokeName = [];
let pokeId = [];
let pokeImg = [];
let pokeType = [];
let pokeMove = [];

(async function () {
    for (let i = 1; i < 21; i++) {
        const data = await fetch(`https://pokeapi.co/api/v2/pokemon/${i}/`);
        const json = data.json();

        pokeId.push(json['id']);
        pokeName.push(json['name']);

        const dataTypes = json['types'];
        pokeType.push(dataTypes[0]['type']['name']);

        const dataMoves = json['moves'];
        pokeMove.push(dataMoves[0]['move']['name']);

        pokeImg.push(json['sprites']['front_default']);
    }
})();


console.log(pokeName);
console.log(pokeId);
console.log(pokeImg);
console.log(pokeMove);
console.log(pokeType);

As I mentioned in my comment, your console.log() code runs before the fetch has returned its promise, and thus no data has been set yet.

for loops actually do not work with the await keyword and so typically you just need to convert your for loop to a for await...of loop instead. Then you can call an async function that loops through all the values you need and once all promises in the loop have been returned, the following code will execute (within the scope of the same function. Any code outside of the function will run asynchronously).

let pokeName = [];
let pokeId = [];
let pokeImg = [];
let pokeType = [];
let pokeMove = [];

let pokeCount = [];
for(let i = 1; i < 21; i++) pokeCount = [...pokeCount, i];

const _FetchPokes = async () => {
  for await (const poke of pokeCount) {
    await fetch(`https://pokeapi.co/api/v2/pokemon/${poke}/`)
      .then(Response => Response.json())
      .then(data => {
        pokeId.push(data['id']);
        pokeName.push(data['name']);
        pokeType.push(data['types'][0]['type']['name']);
        pokeMove.push(data['moves'][0]['move']['name']);
        pokeImg.push(data['sprites']['front_default']);
      });
  }
  
  // This will run AFTER the data has been fetched
  _RunAfterFetch();
}

const _RunAfterFetch = () {
  // Add any code you want to run here
  // This will run AFTER the pokemon data has been fetched
  console.log(pokeName[1-1]);
}

_FetchPokes();

here is the alternate way to fetch data

const getPokemon =async(id)=>{
return await (await fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)).json();
}

const getSerializedData = async () =>{

for (let i=1; i< 10; i++) {
  const data = await getPokemon(i);
  console.log(data)
  }
}


getSerializedData();

Related