ARNON
ARNON

Reputation: 1217

Firestore + Vue: When refreshing the page, how to avoid delay in data display?

Every time I refresh the page, a new query is made in the Firestore database to show (sometimes) the same data to the user.

It is a bookcase. The code below only reads data that has already been added:

export default {
  name: "Shelf",
  date: () => ({ shelfName: "", books: [] }),
  async mounted() {
    const auth = getAuth();
    const db = getFirestore();
    const userID = auth.currentUser.uid;
    const userRef = doc(db, "users", userID);
    const userSnap = await getDoc(userRef);

    userSnap.exists()
      ? (this.shelfName = "Shelf: " + userSnap.data().name)
      : (this.shelfName = "Your Shelf");

    const userBooksRef = query(collection(db, "users", userID, "addedBooks"));
    const querySnapshot = await getDocs(userBooksRef);
    querySnapshot.forEach((doc) => {
      this.books.push({
        id: doc.id,
        addedIn: doc.data().addedIn,
        readIn: doc.data().readIn,
      });
    });

    this.books.map(async (book) => {
      const booksRef = doc(db, "books", book.id);
      const bookSnap = await getDoc(booksRef);

      book.authors = bookSnap.data().authors;
      book.title = bookSnap.data().title;
      book.thumbnail = bookSnap.data().thumbnail;
    });
  },
};

I'm not sure if I should look for a caching solution or if there is some other type of solution. Below I show the books collection. It's important to say that within the users collection there is a collection called addedBooks that reference the id of each book below:

Firestore_Books

Upvotes: 1

Views: 251

Answers (1)

Hydra
Hydra

Reputation: 1000

When refreshing the page, you're destroying the previous instance of your application and loading a new one. As such, your app will re-execute all of its queries just like it did the first time opening the app.

As Estus mentioned in the comments, this problem is often solved by storing your data in state, and then putting that state in localstorage. When your page is refreshed, you first load the state from localstorage (no delay), and then update the state with the current data from your query when it becomes available. You can implement this process manually as well without using a state management library.

When storing data in localstorage, make sure you update it every time the data changes, and clear it when you no longer need it.

Upvotes: 3

Related Questions