如何使用Snapshot方法限制FIrebase Firestore在React JS中的读取

问题描述 投票:0回答:1

我这里有两个主要问题。

(1) 我一直在尝试找到一种方法来 limit() 从 Firestore 读取,但我找不到用快照方法限制它的方法。我们不打算以另一种方式重写整个函数,只是想知道如何将限制添加到当前情况,即每次运行它时,它都显示 limit() 不是一个函数。 因此,当我开发这个应用程序时,我可以只显示 100 个项目,比如说

import { db } from "../utils/firebase.js"
import { collection, doc, setDoc, getDocs, getDoc, deleteDoc, onSnapshot, updateDoc } from "firebase/firestore"

// WORKING ON IT

export function getProduct(fn) {
    const colRef = collection(db, "companyproduct").limit(20).get() // collection name

    onSnapshot(colRef, snapshot => {
        const list = snapshot.docs.map(doc => {
            const d = doc.data() // get data called d
            return {
                id: doc.id, // just add auto-gen ID
                ...d, // put all data into array object
            }
        })

        fn(list)
    })
}

这是在另一个page.js中

    const getData = async () => {
        await getProduct(list => {
            setTableData(list)
            setOriginalData(list) // just start searching from original data
        })
    }

所以基本上,我想做的是一次加载所有 10,000 个产品,然后使用表中的 OnClick 将这些产品添加到 POS 系统并创建发票/收据。话虽如此,它也会改变所售产品的“可用库存”。

所以我的另一个问题是 (2) 无需重新加载页面(因为创建的发票将被视为写入另一个集合,并且 State const [makeInvoice, setMakeInvoice] = useState([]) 将在发票创建后立即被清除)

Firebase 会认为它是重新读取全部 10,000 个产品吗?附:每个已售出产品的库存已经在服务器上更改,但不需要重新加载。

我们尝试通过快照方法限制Firestore中的读取。总的来说,我们喜欢一路改变集合中的数据,同时保持较低的读取量。

reactjs firebase google-cloud-platform google-cloud-firestore limit
1个回答
0
投票

我一直在尝试找到一种方法来 limit() 从 FireStore 读取,但我找不到用快照方法来限制它的方法。我们不打算以另一种方式重写整个函数,只是想知道如何在当前情况下添加限制,即每次运行它时,它都显示

limit()
不是一个函数。

如果您想限制从 Firestore 读取的文档数量,则必须创建一个

query
并将
limit(x)
调用传递给查询函数。所以请更改以下代码行:

const colRef = collection(db, "companyproduct").limit(20).get()

致:

const queryCompanyProduct = query(collection(db, "companyproduct"), limit(20));
onSnapshot(queryCompanyProduct, snapshot => {
    //...
})

Firebase 会认为这是重新读取全部 10,000 个产品吗?

如果您使用

get()
通话,则每次重新加载页面时,都会根据您阅读的文档数量向您计费。

仅当用户失去互联网连接时,查询才会从缓存中读取文档,否则,它将始终读取 Firebase 服务器上存在的文档的在线版本。文档的缓存版本仅在用户离线时才有效。

© www.soinside.com 2019 - 2024. All rights reserved.