简体   繁体   中英

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

How about

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM