//Environment:
//Vue 3
//Vite
//Firebase V9
//Pinia** (For state management)
Hi!, I'm just trying to unsubscribe from firestore listeners from from Pinia Actions... for this matter I'll give a brief example of how is it set it up.
So first in my Pinia Store, I have defined a property where all the listeners (onSnapshot) are stored in order to access the unsubscribe function later from anywhere in my application.
//Pinia store: frontDesk.ts
import {defineStore} from 'pinia'
import {db} from "/@src/firebase/config";
import { collection, query, where, onSnapshot, doc, getDoc, orderBy } from "firebase/firestore";
import {commonStore} from "/@src/stores/stores";
export const useFrontDeskStore = defineStore({
id: 'frontDesk',
state: () => ({
...
listeners: <any>{
...
getAvailability: () => null,
...
}
}),
...
actions: {
...
async getAvailability() {
const q = query(collection(db, commonStore.selectedHotel, "guest", "reservations"), where('noShow', '==', false), where('cancelled', '==', false), orderBy("checkinDate", "desc"));
this.listeners.getAvailability = onSnapshot(q, (docSnapshot) => {
commonStore.masterLoader = true
this.loadingAvailability = true
this.reservations.splice(0, this.reservations.length)
this.occupiedRooms.splice(0, this.occupiedRooms.length)
docSnapshot.forEach((doc) => {
const data = doc.data()
if (rangesOverlaps([this.dateRange?.start, this.dateRange!.end], [firestoreToDate(data.checkinDate), firestoreToDate(data.checkoutDate)])){
this.reservations.push(data)
this.occupiedRooms.push(parseInt(data.roomNumber), ...data.extra_rooms)
}
})
this.getBlockedRooms()
commonStore.masterLoader = false
});
},
...
}
})
Then after checking for user inactivity, I access the unsubscribe function like this:
//FrontDesk.vue
//IDLE
...
import { useIdle } from '@vueuse/core'
const { idle, lastActive } = useIdle(5000) // 5 seconds (for testing purposes)
watch(idle, val => {
idleAction(val)
})
const idleAction = async (isIdle) => {
if (isIdle) {
console.log("Inactivity detected, stopping listeners to save some money")
await frontDeskStore.listeners.getAvailability()
} else {
console.log("Activity detected, re-activating listeners for realtime updates")
await frontDeskStore.getAvailability()
}
}
...
Everything seems to go through with no errors, but then from another client I make some change after the unsubscribe have been fired, and keep getting the real-time updates.
Is there anything I'm missing here?