I am trying to run some firebase code when the tab is closed or refreshed for my react app, and it is working fine so far for firebase, however when I close the tab the code is not executed. I assume this is because firebase is asynchronous, and thus the tab closes before the firebase code is done executing. Is there a way for me to get around this and assure my firebase code finishes execution before the tab closes?
leaveLobby(e) {
e.preventDefault();
var firestore = firebase.firestore();
var docRef = firestore.doc("Games/Game " + this.state.Lobbycode);
docRef.get()
.then((docSnapshot) => {
if (docSnapshot.data().PlayerAmnt === 1) {
firestore.doc("Games/Active Games").update({
"Active Games" : firebase.firestore.FieldValue.arrayRemove(this.state.Lobbycode)
})
firestore.doc("Games/Game " + this.state.Lobbycode).delete();
} else {
docRef.update({
players : firebase.firestore.FieldValue.arrayRemove(this.state.name),
PlayerAmnt : firebase.firestore.FieldValue.increment(-1)
})
}
this.props.setInLobby(false, "", this.state.name);
})
return
}
componentDidMount() {
window.onbeforeunload = this.leaveLobby;
}