NotaGuruDotCom
NotaGuruDotCom

Reputation: 61

How to persist a specific document offline

Using firebase, I have a collection of users, I dont want to persist all users offline for every account but only for that specific users account - is this possible?

I read another answer saying that firebase dictates this and i have no control over it. I have my doubts about that as it seems like a fairly common use case

Upvotes: 0

Views: 45

Answers (3)

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

One solution would be to store the user’s data in the browser local storage. You can do that by using the onAuthStateChanged observer:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
     db.collection("users").doc(user.uid).get()
     .then(snap => {
        localStorage.setItem('userData', JSON.stringify(snap.data()));
     });
  } else {
    // No user is signed in.
  }
});

Upvotes: 0

LeadDreamer
LeadDreamer

Reputation: 3499

The most important part of Doug's answer is "...anything your app reads...". The Firestore offline persistence cache DOES NOT fetch all, or even a significant part, or even ANY of your database until you execute read or write operations. If your app only reads the authorized user's documents, only those documents will be in your cache.

IF you are fetching all user documents for each user's app, you really need to ask yourself "Why?!?" - especially that is in-and-of-itself a security problem.

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317372

If you are referring to Firestore's offline persistence cache, it's true that you don't have specific control over what it caches. It will cache anything that your app reads, and store it for as long as it sees fit.

If you have specific caching needs that are not met by the Firestore SDK, you should consider disabling the cache and implement something yourself.

Upvotes: 1

Related Questions