0

I need to merge objects that came from the API response. I tried the push function to join those response objects in one array but it always gives the result as an empty Array. I did this last week and until now there is no luck. I need help.

Here is my code:

var finaldata = []
await fetch("https://api-getting-the-ID")
  .then(res => res.json())
  .then(
    (result) => {
      return result.map(({ id }) => id)
    },
  ).then(ids => {
    ids.map((id, key) => {
      fetch(`https://myAPI/${id}`)
        .then(res => res.json())
        .then((response) => {
          finaldata.push(response)
        }),
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
    });
   this.setState({
      isLoaded: true,
      items: finaldata
    });
  })

Thank you in advance!

  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – derpirscher Jan 21 '23 at 10:12
  • you are never awaiting the `fetch`es insinde `ids.map(...)`. Thus, `this.setState` is executed way before these requests are finished ... – derpirscher Jan 21 '23 at 10:15
  • 1
    Btw. you should not mix `async/await` with `.then().catch()` unless you exactly know what you are doing. And if know what you are doing, you probably know better than mixing those two. Because it leads to situations like yours ... – derpirscher Jan 21 '23 at 10:16

1 Answers1

2

I think your finaldata array is being filled after you have put it into state. Try something like this:

const idData = await fetch("https://api-getting-the-ID").then(r => r.json())
const ids = idData.map(data => data.id)
try{
  const promises = ids.map(id => fetch(`https://myAPI/${id}`).then(r => r.json())
  const items = await Promise.all(promises)
  this.setState({isLoaded: true, items})
} catch(error){
  this.setState({isLoaded: true, error});
}
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34