I have a react app where I want to delete a user from the database if he leaves the session. I tried doing that with onUnload but it doesn't call the method at all. Part of the code that is relevant:
componentDidMount() {
window.addEventListener("beforeunload", this.onUnload);
}
componentWillUnmount() {
window.removeEventListener("beforeunload", this.onUnload);
}
onUnload = ev => { // the method that will be used for both add and remove event
const db = firebase.firestore();
db.collection('parties').doc(this.state.partyNum).get().then(res=>{
const result = res.data();
if(result.users.length===1){
db.collection('parties').doc(this.state.partyNum).delete()
}else{
db.collection('parties').doc(this.state.partyNum).update({
users: firebase.firestore.FieldValue.arrayRemove(this.state.username)
}).then(()=>{
this.setState({unconfirmed: false})
})
}
})
I also tried with binding and no arrow functions but it didn't work
In my reproduction of problem, I put console.log inside
onUnloadand visit the pageWhen I visited the page, I made sure
addis in console. Then I navigate to another url. I sawhandler firedin console for a brief moment. Which means event handler was fired.But you run async code, so I think your network call gets cancelled during unload event. Also
async awaitmight help (i havent tried sorry, im on my phone)Also worth noting:
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload