How to delete a Firestore doc when user closes tab in React?

Viewed 189

I need to delete a document in Firestore when a user closes their tab. I am using React.

I am adding an event listener in useEffect to prompt the user if they really want to leave.

window.addEventListener('beforeunload', (event) => {
  event.returnValue = `If you leave you cannot join again! Are you sure? `;
});

What I really need is to delete a doc in Firstore if the user confirms they want to leave. I am trying firing the delete code in the return of useEffect but it's not working.

return () => {
  currentGame.collection("players").doc(userId).delete()
    .then(function () {
      console.log("Document successfully deleted!");
    }).catch(function (error) {
      console.error("Error removing document: ", error);
    });

}

Is there any way I can update Firestore when a user closes their tab?

0 Answers
Related