Search code examples
javascriptreactjsfirebaseonunload

beforeUnload does not call


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


Solution

  • In my reproduction of problem, I put console.log inside onUnload and visit the page

    componentDidMount() {
        console.log('add')
        window.addEventListener("beforeunload", this.onUnload);
    }
     
    componentWillUnmount() {
        console.log('add')
        window.removeEventListener("beforeunload", this.onUnload);
    }
    
    onUnload = ev => { 
        console.log('handler fired')
    }
    

    When I visited the page, I made sure add is in console. Then I navigate to another url. I saw handler fired in 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 await might help (i havent tried sorry, im on my phone)

    Also worth noting:
    https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

    When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example: