Before doing anything else, remember to call the function enableIndexedDbPersistence(db)
. Here's what the documentation says:
This function must be called before any other functions (except for
{@link initializeFirestore}, {@link (getFirestore:1)}, or
{@link clearIndexedDbPersistence}.
However, it seems that the function getFirestore(app)
is an exception to this rule, despite what you may have thought based on your comment in the code snippet:
// >>> if put here it said can't be invoked after getFirestore or any other function
It appears that you may be trying to use the exported db
variable before the promise from enableIndexedDbPersistence(db)
has finished. To fix this, consider wrapping the code in a service or method and ensuring that you are using await
with the promise, or structuring your app so that db
isn't immediately accessed.
In my Ionic PWA application, I've successfully implemented the following approach:
import { getFirestore, enableIndexedDbPersistence } from "firebase/firestore";
import { initializeApp } from "firebase/app";
const firebaseConfig = {
// ...
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
enableIndexedDbPersistence(db)
.then(() => console.log("Enabled offline persistence"))
.catch((error) => {
if (error.code == "failed-precondition") {
// Multiple tabs open, only one tab can enable persistence at a time.
// ...
} else if (error.code == "unimplemented") {
// The current browser does not support all the necessary features for persistence
// ...
}
});
While this setup may resemble yours, the key difference is that Firestore is first accessed in response to user interaction, rather than immediately.