frankcollins3 / PHPokedex

react concepts
0 stars 0 forks source link

data logged to console but unaccessible through bucket[0] bracket notation [2:20pm] #45

Closed frankcollins3 closed 1 year ago

frankcollins3 commented 1 year ago

// HUGE PROBLEM with this loop ---> it returns an empty bucket [] that logs the data but cant retrieve the data from bucket. so annoying. const loopPushFail = async () => { await allAPI.forEach(async(pokemon) => { let predata_allDataAllPoke = await fetch(http://localhost:5000/pokemon?query={allDataAllPokemon(name:"${pokemon.name}"){name,poke_id,type,moves,abilities,image}}) // let predata_allDataAllPoke = await fetch(http://localhost:5000/pokemon?query={allDataAllPokemon(name:${pokemon.name}){name,poke_id}}) let allDataAllPoke = await predata_allDataAllPoke.json()
allDataAllPoke = allDataAllPoke.data.allDataAllPokemon
await bucket.push(allDataAllPoke) // .bucket.push({...allDataAllPoke})
})
}

let bucket = [] bucket.length = 0;

// all of the data can be seen in the bucket but .length is returned as 0. bucket[0] doesn't do anything.

let bucket = ['test', 'another-test']

// even with the addition of 2 strings into the array, those manually entered strings are accessible, while the loop data isn't.

frankcollins3 commented 1 year ago

a viable solution: to invoke an overarching Promise.all() method from which the API.forEach() loop is run. the problem is the data wasn't getting to the bucket and it would have been useful to wait for the data. hence promise.resolve()

const loopAndPush = async () => {
  await Promise.all(allAPI.map(async (pokemon) => {
    let predata_allDataAllPoke = await fetch(`http://localhost:5000/pokemon?query={allDataAllPokemon(name:"${pokemon.name}"){name,poke_id,type,moves,abilities,image}}`)
    let allDataAllPoke = await predata_allDataAllPoke.json()            
    allDataAllPoke = allDataAllPoke.data.allDataAllPokemon

    let myobject = {
      name: allDataAllPoke.name, poke_id: allDataAllPoke.poke_id,  image: allDataAllPoke.image, moves: allDataAllPoke.moves,
      abilities: allDataAllPoke.abilities, type: allDataAllPoke.type
    }

    bucket.push(myobject);                    
  }));
}

[3:38pm]