简体   繁体   中英

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

I currently have a really small web app in which users can make song requests. In Firestore I have a collection called songRequests and every request is a document.

For the admin, I created a dashboard in which he can see the incoming song requests. To try it out I used a onSnapshot listener which correctly shows all requests once the component gets mounted, also when I add a new song it gets added properly and it only reads the newly added document.

The collection currently has around 10 documents and after a refresh, I get 10 full reads, 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?

    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?

While saving the data locally, is indeed a good solution, remember that also Firestore has its own caching mechanism :

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

Besides that, you can also specify the source of your readings. There are three options, CACHE, DEFAULT, and SERVER. However, if try to read the data only from the cache, you'll lose the updates that are coming from the server. If you want to limit the number of reads, I recommend you read the following article:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM