Firebase RTDB ' ref.once() '被多次执行

Firebase RTDB `ref.once()` being executed multiple times

本文关键字:执行 once RTDB ref Firebase      更新时间:2023-09-26

最近玩firebase RTDB,我一直在使用.once('value', v => ...)来构建我的应用程序的GUI。确切的代码如下:

<script>
  function onAuthCompleted(usr) {
    var salesTxRef = firebaseApp.database().ref('/salesTx').limitToLast(5);
    salesTxRef.once("value", salesTx => {
      salesTx.forEach(txRef => {
        const tx = txRef.val();
        const $item = $('<li></li>').html('<a href="' + txRef.key + '">$' + tx.total + ' <small>' + tx.currencyCode + '</small></a>');
        $('.main ul').append($item);
      });
    });
  }
</script>

问题是,如果我让页面打开足够长的时间,.once()被调用多次(每2-3小时一次)。这是javascript库上的一个bug吗?已知的问题?是我做错了什么,还是我有什么误解?

正如@Frank van Puffelen在评论中指出的,问题来自于调用onAuthCompleted(usr)的方法:

firebaseApp.auth().onAuthStateChanged(function(user) {
  if (user) {
    if (typeof onAuthCompleted == 'function') { 
      onAuthCompleted(user); 
    }
  } else {
    console.log('User is not logged in. Cannot start session.');
  }
}, function(error) {
  console.log(error);
});

每小时调用onAuthStateChanged()以刷新会话导致onAuthCompleted()再次被调用,从而再次注册.once()方法(每~小时)。这导致了奇怪的感知行为。

我可以确认.once()按预期工作,这是我对onAuthStateChange()如何工作的误解。

谢谢,