首页 > 解决方案 > 当更改为本地时,onSnapshot fromCache 始终为 false

问题描述

根据这里的描述, 我希望snapshot.metadata.fromCachetrue正在收听的文档与侦听器在同一个客户端中被修改时,例如

  1. 本地.update(...) 立即触发处理程序(并收到设置为onSnapshot的快照)fromCachetrue
  2. 数据被发送到数据库
  3. firebase 客户端收到返回消息并且什么都不做(不触发 a onSnapshot),因为服务器数据与缓存一致。

因此,fromCache应该始终true在 onSnapshot 由本地更改触发时出现。

然而,这似乎只是前两到三个 onSnapshot 响应的情况,之后fromCache似乎总是false.

示例测试:


// ... firestore init w/ a test project and with persistence enabled. 

const db = firebase.firestore();
db.settings({
    ignoreUndefinedProperties:true
})

// Where "_test" is an empty collection with full allowance for read/write
await db.collection("_test").doc("deleteme").set({}); 

let doc = db.collection("_test").doc("deleteme") 

// ?! Expect this to be true but after the first one or two occurrences it is always false.
doc.onSnapshot(s=>{console.log("test snapshot change from cache? ",s.metadata.fromCache)}) 

let x = 0;      
let poke = async ()=>{
  doc.update({
    n:Math.random()
  })
  await sleep(3000); // generic custom delay 
  window.requestAnimationFrame(poke)
};
window.requestAnimationFrame(poke);

编辑:这里的问题是由于与其他问题类似地缺少知识:Firestore onSnapshot update event due to local client Set?

标签: javascriptgoogle-cloud-firestore

解决方案


因此,当 onSnapshot 由本地更改触发时,fromCache 应该始终为真。

我不认为它是这样定义的。客户端是否知道其本地快照是否与服务器同步更重要。

你可能会混淆fromCache. hasPendingWrites名字fromCache确实让人迷惑。我理解fromCache为“可能尚未包含来自服务器的所有数据”,而isPending“可能包含服务器尚不知道的数据”。


推荐阅读