【问题标题】:Can not enableIndexedDbPersistence from firebase v9 in a nextjs pwa无法在 nextjs pwa 中从 firebase v9 启用 IndexedDbPersistence
【发布时间】:2022-11-27 00:17:37
【问题描述】:
我不能在 nextjs pwa 中使用 firebase v9 enableIndexedDbPersistence。
这个错误是错误的
index.js // firebase 主
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getFirestore } from 'firebase/firestore'
import { getStorage } from 'firebase/storage'
const firebaseConfig =
process.env.NEXT_PUBLIC_FIREBASE_CONFIG
const app = initializeApp(JSON.parse(firebaseConfig))
export const db = getFirestore(app)
// enableIndexedDbPersistence(db) // >>> if put here it said can't be invoked after getFirestore or any other funtion
export const auth = getAuth(app)
export const storage = getStorage(app)
那么我应该在哪里调用
【问题讨论】:
标签:
javascript
firebase
google-cloud-firestore
next.js
progressive-web-apps
【解决方案1】:
enableIndexedDbPersistence(db)函数必须在之前调用。从它的文档:
必须在任何其他函数(除了
{@link initializeFirestore}、{@link (getFirestore:1)} 或
{@link clearIndexedDbPersistence}。
所以 getFirestore(app) 实际上是豁免的,与你在代码注释中所说的截断相反:
// >>> if put here it said can't be invoked after getFirestore or any other function
因此,我的猜测是您可能会在 enableIndexedDbPersistence(db) 的承诺完成之前使用导出的 db。
您可以通过不同的方式解决此问题,例如将其包装在服务或方法中并确保您 await-ing 承诺,或者通常更改您的应用程序以确保 db 未立即使用。
在我的 Ionic PWA 应用程序中,我成功地使用了以下内容:
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, persistence can only be enabled
// in one tab at a a time.
// ...
} else if (error.code == "unimplemented") {
// The current browser does not support all of the
// features required to enable persistence
// ...
}
});
这确实与您的剪辑非常相似。但是第一次访问 Firestore 是在通过用户交互之后发生的,而不是马上。