Asaf Hadad
Asaf Hadad

Reputation: 25

react setState hook with async map

I'm trying to use a setState hook with a map on an array where one of the properties of the final object is an async function

setState(
 _exports.map(async (exportData) => {
  const ruleStatus = await getMonitorData(exportData)
  return {
   ...exportData,
   ruleStatus
  }
 })
)

const getMonitorData = async (_export) =< {
 return post('/app/monitor', _export)
}

but all I'm getting is an array of pending promises and the page renders without the actual content (everything is undefined) I would like to wait for the post to finish and use the actual response instead of the pending promise I'm getting

Upvotes: 0

Views: 540

Answers (1)

TheWhiteFang
TheWhiteFang

Reputation: 783

How about

const promises = _exports.map(async (exportData) => {
    const ruleStatus = await getMonitorData(exportData)
    return {
        ...exportData,
        ruleStatus
    }
})
Promise.all(promises).then(setState)

Upvotes: 1

Related Questions