Reputation: 757
I am currently building my app using React native Expo. In my app I have to save my user's entries into the database. Since my users may not have a consistent internet connection, I was looking for a database service which can handle offline scenarios out of the box. And Firebase's Firestore came as a natural choice. Read here how firestore offline mode works.
So I went ahead and implemented the firestore in my app, everything worked as expected. But in offline mode firestore did show any data. It also doesn't throw any error either.
Here's my very simple firestore setup
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { firebaseConfig } from "./config";
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
Here's how I am fetching the data from the firestore
import { db } from "../index";
import {
collection,
doc,
getDoc,
QueryDocumentSnapshot,
} from "firebase/firestore";
export const firestoreService = {
get: async <T>(collectionName: string, id: string): Promise<T | null> => {
const docSnap = await getDoc(doc(db, collectionName, id));
return docSnap.exists() ? (docSnap.data() as T) : null;
},
}
This code works perfectly fine when an internet connection is available but as soon as the device goes into offline mode it gives an empty object.
As per official document, firestore should work in offline mode without any additional code change when it comes to android or IOS apps. But it is not working in my expo app.
I tried various options such as getDocsFromCache()
method,hoping it will return cached data at least then I can manually handle offline scenario. But it did not work.
getAll: async <T>(collectionName: string): Promise<T[]> => {
const querySnapshot = await getDocsFromCache(collection(db, collectionName));
return querySnapshot.docs.map(
(doc) => ({ id: doc.id, ...doc.data() } as T)
);
},
Here's how I am testing the offline mode
How can I make it work in offline mode?
Upvotes: 0
Views: 328
Reputation: 599866
You're using the web SDK of Firebase, where offline caching is not enabled by default. From the docs on configuring offline persistence:
For the web, offline persistence is disabled by default. To enable persistence, call the
enablePersistence
method.
That section also contains code on how to enable offline persistence in the web SDK.
Upvotes: 0