Firestore onSnapshot Unsubscribe Not Triggered on Page Refresh

Discussão em 'Angular' iniciado por Just Away, Dezembro 8, 2024.

  1. Just Away

    Just Away Guest

    I'm experiencing an issue with Firestore's onSnapshot listener not unsubscribing when a page is refreshed or closed. I'm using Angular and the Firestore SDK, and I've implemented the unsubscribe logic within the beforeunload event. However, the unsubscribe function provided by Firestore doesn't always seem to execute, as evidenced by inconsistent request logs in the Firestore emulator and chrome's network monitoring. And even when it does I see no "ListenHandler onClose" in the emulator logs. The unsubscribe not working is also evident by the multiplying requests fire on a single change in a firestore document on each refresh. This issue is not reproduced when calling the unsubscribe upon calling unsubscribe directly (upon user logout per example)

    @HostListener('window:beforeunload', ['$event'])
    unloadHandler(event: Event) {
    this.unsubscribeFromFirestore();
    }

    ngOnDestroy() {
    this.unsubscribeFromFirestore();
    }

    unsubscribeFromFirestore() {
    if (this.unsubscribe) {
    console.log('Unsubscribing from Firestore');
    this.unsubscribe(); // Directly call the unsubscribe function
    }
    }


    Question: How can I ensure that the Firestore onSnapshot unsubscribe function is reliably called during a page refresh or close? Are there any best practices or alternative approaches to handle this scenario effectively?

    Continue reading...

Compartilhe esta Página