how to convert this code to realtime data firestore, this code work well but is not realtime. i need realtime read for my datatable.
useEffect(() => {
setLoading(true)
const date = new Date()
const januari = new Date(date.getFullYear(), 0)
const juni = new Date(date.getFullYear(), 5 1, 0)
const tahunSekarang = date.getFullYear()
const tahunSetelah = date.getFullYear() 1
const tahunSebelum = date.getFullYear() - 1
const pengunjungRef = firebase
.firestore()
.doc(
date >= januari && date <= juni
? 'pengunjung/genap'
: 'pengunjung/ganjil'
)
firebase
.firestore()
.collectionGroup(
date >= januari && date <= juni
? `${tahunSebelum}_${tahunSekarang}`
: `${tahunSekarang}_${tahunSetelah}`
)
.orderBy(firebase.firestore.FieldPath.documentId())
.startAt(pengunjungRef.path)
.endAt(pengunjungRef.path '\uf8ff')
.get()
.then((querySnapshot) => {
let list = []
querySnapshot.forEach((doc) => {
list.push({ id: doc.id, ...doc.data() })
})
setData(list)
setLoading(false)
})
.catch((err) => {
console.error('failed to execute query', err)
})
}, [])
i try this with onSnapshot from firestore documentation but its not work and show error, i try onSnapshot on simple query its work, but when i try to this query group code its show error.
firebase
.firestore()
.collectionGroup(
date >= januari && date <= juni
? `${tahunSebelum}_${tahunSekarang}`
: `${tahunSekarang}_${tahunSetelah}`
)
.orderBy(firebase.firestore.FieldPath.documentId())
.startAt(pengunjungRef.path)
.endAt(pengunjungRef.path '\uf8ff')
.onSnapshot((querySnapshot) => {
let list = []
querySnapshot.forEach((doc) => {
list.push({ id: doc.id, ...doc.data() })
})
setData(list)
setLoading(false)
})
.catch((err) => {
console.error('failed to execute query', err)
})
Error in the console:
firebase_compat_app__WEBPACK_IMPORTED_MODULE_15__.default.firestore(...).collectionGroup(...).orderBy(...).startAt(...).endAt(...).onSnapshot(...).catch is not a function
CodePudding user response:
The onSnapshot()
does not return a Promise so you can't add a catch()
there. The code should work after removing the .catch()
.