I'm a bit stuck on the middle portion of my code. I know what I want the end to look like, and the beginning, but cannot seem to fill in the blank.
I call fetch
on 4 API endpoints, and store the Promises
into a relevant key that tells me what they are.
Then I loop through all of those using a for in
loop, and push all those Promises
into an array so I can call Promise.all
on them.
After successfully logging the array to the console, I see now that the array is filled with objects with my data. However, there is no way for me to tell which data belongs to what object key, like in the original object.
Is there a better way to do this? I do know for a fact that I want to use Promise.all
here in this code; that's something I don't want to budge on, because I am trying to figure out how I can make this possible without giving up (been at this for a couple hours now).
At the end of my code (this is just pseudocode for a real life example in my React app), I just want to take the final object, and push it into state
.
Any help is appreciated.
//imitating React State as an example
const state = {
iliakan: '',
remy: '',
jeresig: '',
}
//put all of the urls in an object with a key-pair value to describe the data
const githubAPI = {
iliakan: 'https://api.github.com/users/iliakan',
remy: 'https://api.github.com/users/remy',
jeresig: 'https://api.github.com/users/jeresig'
}
//create an empty object to assign promises to keys
const movieData = {};
const promiseArr = [];
//store promise into relevant key
for (const user in githubAPI) {
movieData[user] = fetch().then(res => res.json())
}
//now movieData has keys with values set to related Promises
console.log(movieData);
//loop through these promises, and put them in an Array for Promise.all
for (const userData in movieData) {
promiseArr.push(movieData[userData])
}
//Use Promise.all on all of those promises
Promise.all(promiseArr).then(responseArr => console.log(responseArr);
//this is where I am stuck. I now have an array of objects with all the correct data, but I don't know how to reassign them back to their original, matching key that they had in the movieData object!
//end goal is to have an object like this
//const movieData = {
// iliakan: {//object with data from api},
// remy: {//object with data from api},
// jeresig: {//object with data from api}
//}
//use the movieData to setState and update current component state