通过在本地保存数据并将其与 Firestore 中的数据进行比较来减少 Firestore 读取?

Reduce firestore reads by saving data locally and comparing it against the data in Firestore?

我目前有一个非常小的网络应用程序,用户可以在其中请求歌曲。在 Firestore 中,我有一个名为 songRequests 的集合,每个请求都是一个文档。

对于管理员,我创建了一个仪表板,他可以在其中查看传入的歌曲请求。为了尝试它,我使用了一个 onSnapshot 侦听器,一旦安装了组件,它就会正确显示所有请求,而且当我添加一首新歌曲时,它也会正确添加,并且它只会读取新添加的文档。

该集合目前有大约 10 个文档,刷新后,我得到 10 个完整读取,我想知道是否可以将其保存在本地并与集合中的数据进行比较,以防止它读取所有内容每次刷新时集合中的文档?

    const [songs, setSongs] = useState([]);
  useEffect(() => {

    // getDocuments();

    const unsub = onSnapshot(collection(db, "songrequests"), (snapshot) => {
      snapshot.docChanges().forEach((change) => {
        if (change.type === "added") {
          const newItem = change.doc.data();
          console.log(newItem);
          setSongs((prevState) => [...prevState, newItem]);
        }
      });
    });

    return unsub;
  }, []);

I was wondering if it is possible to save it locally and compare it against the data in the collection to prevent it from reading all of the documents in the collection on every refresh?

虽然将数据保存在本地,确实是一个很好的解决方案,请记住 Firestore 也有其 own caching mechanism:

For the web, offline persistence is disabled by default. To enable persistence, call the enablePersistence method.

除此之外,您还可以指定阅读的来源。共有三个选项,CACHE、DEFAULT 和 SERVER。但是,如果尝试仅从缓存中读取数据,您将丢失来自服务器的更新。如果你想限制阅读次数,推荐你看下面这篇文章: