Home > front end >  react setState hook with async map
react setState hook with async map

Time:01-17

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

CodePudding user response:

How about

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