[英]How to get data from Firestore Document Reference with realtime updates in React
[英]How to get realtime updates for a subcollection in firestore?
我的數據庫包含一個名為“已觀看”的子集合,用於觀看視頻。 我希望能夠實時跟蹤此類子集合。 路徑如下所示: users/userDocument/watched/date/nestedObjectsForMoviesWatched
例如users/as7f9as98dfa/watched/June-2020/ {name: Forrest Gump, watched: true} {name: Interstellar, watched: false}
這是我嘗試處理的方法
useEffect(() => {
const unsubscribeWatched = firebase
.firestore()
.collection('users')
.doc(userId)
.collection('watched') //why doesn't this work?
.doc(month)
.onSnapshot(snapshot => {
//how to handle snapshot received?
})
return () => {
unsubscribeWatched()
}
}, [])
特別重要的是,我的應用程序知道何時對給定 object 中的watched
屬性進行了更改。
該文檔似乎可以幫助您執行所需的任務。 正如您在共享鏈接中所見,“如果您想在文檔或查詢元數據更改時接收快照事件,請在附加偵聽器時傳遞偵聽選項 object”。 因此,只需在代碼中添加“includeMetadataChanges: true”,如下所示。 完整的例子可以在這里找到。
useEffect(() => {
const unsubscribeWatched = firebase
.firestore()
.collection('users')
.doc(userId)
.collection('watched')
.doc(month)
.onSnapshot(snapshot => {
includeMetadataChanges: true
})
return () => {
unsubscribeWatched()
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.