Reputation: 121
I'm having difficulty accessing the values from getPeople(0,4).
function getPeople(start, end) {
const peopleArray = [];
for (let i = start; i <= end; i++) {
peopleArray.push(
axios.get(`https://www.testsite.net/api/test/workers/${i}`)
);
}
return peopleArray;
}
useEffect(() => {
Promise.all([getData(), getPeople(0, 4)]).then(item => {
//console.log(item[0].data.orders); //
setData(item);
setPersonData(item);
});
}, []);
item[0]
works fine.
Here's the result I'm getting when I console.log(item[1])
How can I access the data?
item[1]
is an array of promises.
Upvotes: 1
Views: 80
Reputation: 1507
This is can be made more readable using an async function in useEffect
//make sure this actually returns the people rather than a load of promises
async function getPeople(start, end) {
const peopleArray = [];
for (let i = start; i <= end; i++) {
let person = await axios.get(`https://www.hatchways.io/api/assessment/workers/${i}`);
peopleArray.push(person);
}
return peopleArray;
}
//then in useEffect you need to create another async function
useEffect(() => {
async function getDataAndPersons() {
const data = await getData();
setData(data);
const people = await getPeople(0, 4);
people.forEach(person => setPersonData(person));
};
getDataAndPersons();
}, []);
Upvotes: 0
Reputation: 4741
You simply need to spread the array returned from getPeople()
like so:
Promise.all([getData(), ...getPeople(0, 4)]).then(item => {
console.log(item);
});
Promise.all()
expects an array of Promise
, you were passing an array containing another array.
Upvotes: 3
Reputation: 7017
The getPeople
function returns an array of promises.
If you want to await those promises in the Promise.all
call, one option is to:
useEffect(() => {
Promise.all([getData(), ...getPeople(0, 4)]).then(item => {
//console.log(item[0].data.orders);
console.log(item[1]); // this will effectively output the people 0 object
setData(item);
setPersonData(item);
});
}, []);
The above will receive as item[0]
the resolved value from the promise of getData
(which sounds expected already). Then item[1]
through item[5]
will be the 5 people objects you seem to be expecting.
Upvotes: 0