Running Firebase code when closing tab (React)

Viewed 240

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;
}
1 Answers

You can hook into the close event

window.addEventListener("beforeunload", (ev) => 
{  
    ev.preventDefault();
    return ev.returnValue = 'Are you sure you want to close?';
});

componentDidMount: function() {
    window.addEventListener('onbeforeunload', this.handleWindowClose);
},

componentWillUnmount: function() {
    window.removeEventListener('onbeforeunload', this.handleWindowClose);
}

Just make sure you also store the handler in a local field during initialization in the constructor

  • this.handler = (ev) =>

Then use the following as needed

  • addEventListener("beforeunload", this.handler)
  • removeEventListener("beforeunload", this.handler)
Related