1

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.

enter image description here

3 Answers3

3

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.

emeraldsanto
  • 4,330
  • 1
  • 12
  • 25
0

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.

Will
  • 6,601
  • 3
  • 31
  • 42
0

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();
}, []);
Tom
  • 1,447
  • 1
  • 12
  • 26