gpt4 book ai didi

javascript - 如何在 reactfire 上启用持久性?

转载 作者:行者123 更新时间:2023-12-04 08:23:43 26 4
gpt4 key购买 nike

我想使用 reactfire 在我的 PWA React 应用程序上实现 Firestore 离线持久性图书馆。

const firestore = useFirestore().enablePersistence();

let documentReference = firestore
.collection("food")
.doc("milkshake");

const { data } = useFirestoreDocData(documentReference);
但运行代码我得到一个错误:

FirebaseError: Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.


这个组件被包裹在 <Suspense> 中。如文档中所述
该数据库读取是我在整个应用程序中制作的唯一一个,我该如何解决?
编辑。
使用@Ajordat 给出的示例,我已经导入了 preloadFirestore App 组件中的函数我确实收到错误:

"Cannot read property 'name' of undefined".


而适应(因为我不能在 fetch 函数中使用钩子(Hook))
@DougStevenson 的例子:我已经导入了 useFirestore App 中的函数组件(为了获取 Firestore 对象)以启用持久性,然后将它( useFirestore )导入我的组件中以检索数据,但是现在,我得到与以前相同的错误,

Firestore has already been started and persistence can no longer be enabled.


编辑2:
我已经尝试无错误地启用Persistence,谢谢大家,这是我的方法,如果它是最好的,请告诉我:
const firestore = useFirestore();

React.useEffect(() => {
firestore.enablePersistence();
}, []);
在我的自定义组件中:
let docRef = useFirestore()
.collection("food")
.doc("milkshake");

let document = useFirestoreDocDataOnce(docRef);
console.log(document)

但是现在我确实有一个问题,当我记录文档时,数据不会立即发出,是的,我知道这是一个异步操作,但是组件被包裹在 <Suspense> 中, 这样:
<Suspense fallback={<div>Loading</div>}>
<FoodComponent foodName={"Milkshake"} />
</Suspense>
但是在组件实际渲染之前我没有看到加载文本。
悬念片段是否仅在加载函数(useFirestore)而不是实际数据时显示回退组件?
好吧,我已经解决了,必须解构数据,这样做:
let docRef = useFirestore()
.collection("food")
.doc("milkshake");

let { data: document } = useFirestoreDocData(docRef);
console.log(document)

最佳答案

在 Firestore 的其他 JavaScript 库中,enablePersistence()返回一个 promise 。这意味着它将在 future 一段时间内完成,但无法保证需要多长时间。如果您正在执行查询 立即在你调用 enablePersistence() 之后,无需等待返回的 Promise 完成,你就会看到这个错误信息。这是因为查询“击败”了持久层并首先有效执行。
您将必须弄清楚如何使用该 promise 等到可以在启用持久性的情况下进行该查询。例如:

seFirestore().enablePersistence()
.then(() => {
let documentReference = firestore
.collection("food")
.doc("milkshake");
const { data } = useFirestoreDocData(documentReference);
})
.catch(error => {
console.error("enablePersistence failed", error);
})
请注意只有在完全启用持久性后查询才会完成。

关于javascript - 如何在 reactfire 上启用持久性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65375743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com