Wait for all promises to resolve before updating state and redirect

Viewed 102

The .then() in my code below is triggered after one image is uploaded. At that time it is too early to update my state variable and make a redirect. I should wait for all files to be uploaded before proceeding. Can someone point me in a direction to accomplish this?

 const storageRef = app.storage()
 const [files, setFiles] = useState([])
 const [data, setData] = React.useState()

  const handleSubmit = () => {
    files.forEach((file) => {
      storageRef
        .ref(`${data.firebaseRef}/${file.id}`)
        .put(file)
        .then(() => {
          // Only if all files are uploaded to firebase then I need to do something
        })
    })
  }

Thanks in advance!

1 Answers

Use Promise.all() to wait for all promises to resolve before doing something else:

const handleSubmit = () => {
  Promise.all(files.map(file =>
    storageRef
      .ref(`${data.firebaseRef}/${file.id}`)
      .put(file)
  )).then(() => {
    // Only if all files are uploaded to firebase then I need to do something
  })
}
Related