Home > Software design >  How to reload the page after a Firebase delete request has executed
How to reload the page after a Firebase delete request has executed

Time:04-10

I have a method that sends a delete request to my Firebase collection. I want the page to reload after the delete request has gone through and the doc is deleted. As it is now, the page reloads immediately and the doc doesn't delete but it works fine if I remove the reload part of the code.

async deletePost() {
  database.collection("posts").where("id", "==", this.id).get().then(data => {
    data.forEach(doc => {
      doc.ref.delete()
    })
  }).then(() => {
    M.toast({
      classes: "toast-alert",
      html: "Post deleted"
    })
  }).then(
    window.location.reload()
  )
}

CodePudding user response:

Each delete() call is asynchronous, so you need for all of them to complete. The solution for this is to use Promise.all on the return values you get from delete():

async deletePost() {
  return database.collection("posts").where("id", "==", this.id).get().then(data => {
    const promises = data.docs.map(doc => doc.ref.delete());
    return Promise.all(promises);
  }).then(() => {
    window.location.reload()
  )
}
  • Related