Home > front end >  JavaScript - Merge objects from API fetch
JavaScript - Merge objects from API fetch

Time:01-22

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!

CodePudding user response:

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});
}
  • Related