In my SvelteKit project, I have integrated Firebase Firestore. I maintain a db.js file that contains various functions utilized in Svelte components. One such function is detailed below.
export const Items = {
async getMany() {
let dbRef = db.collection('items')
try {
const snap = await dbRef.get()
return snap.docs.map(doc => ({ ...doc.data(), id: doc.id }))
} catch (error) {
console.log('Error')
}
},
},
When implementing this function in a Svelte component's onMount lifecycle hook, I fetch the items and assign them accordingly.
let items = []
onMount(() => {
Items.getMany().then(res => {
if (res.length !== 0) {
items = res
}
})
})
This setup has been functioning smoothly for me.
Now, I am striving to develop a method within db.js that enables me to utilize a snapshot listener with onSnapshot from Firebase Firestore. My goal is to acquire both the unsubscribe function and the array of items as return values. How can I modify Items.getMany() to deliver both the unsubscribe functionality and an array of items, which I can then set in the Svelte component similar to what is illustrated below?
let items = []
let unsubscribe = function () {
return
}
onMount(() => {
Items.getMany().then(res => {
unsubscribe = res.unsubscribe
if (res.length !== 0) {
items = res
}
})
})
I've managed to implement this directly within the component and it performs effectively. However, I encounter difficulties when attempting to incorporate it into db.js. Despite experimenting with returning an object containing { unsubscribe, items }, I have not achieved success. Any assistance would be greatly appreciated.
let unsubscribe = function () {
return
}
let items = []
onMount(() => {
Items.getMany().then(res => {
let dbRef = db.collection('items')
unsubscribe = dbRef.onSnapshot(snapshot => {
items = snapshot.docs.map(doc => ({ ...doc.data(), id: doc.id }))
})
})