在查询组集合上实现 onSnapshot 以读取实时 firestore react js

impelement onSnapshot on query group collection for read realtime firestore react js

如何将此代码转换为实时数据 Firestore,此代码运行良好但不是实时的。我需要实时读取我的数据表。

    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)
        })
}, [])

我尝试使用 firestore 文档中的 onSnapshot 进行此操作,但它不起作用并显示错误,我在简单查询上尝试 onSnapshot 它的工作,但是当我尝试此查询组代码时显示错误。

 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)
        })

控制台错误:

firebase_compat_app__WEBPACK_IMPORTED_MODULE_15__.default.firestore(...).collectionGroup(...).orderBy(...).startAt(...).endAt(...).onSnapshot(...).catch is not a function

onSnapshot() does not return a Promise 所以你不能在那里添加 catch()。删除 .catch().

后代码应该可以工作