Firebase child_added for new items only

前端 未结 5 1175
北恋
北恋 2020-12-15 18:46

I am using Firebase and Node with Redux. I am loading all objects from a key as follows.

firebaseDb.child(\'invites\').on(\'child_added\', snapshot => {
}         


        
5条回答
  •  旧巷少年郎
    2020-12-15 18:51

    Although the limit method is pretty good and efficient, but you still need to add a check to the child_added for the last item that will be grabbed. Also I don't know if it's still the case, but you might get "old" events from previously deleted items, so you might need to watch at for this too.

    Other solutions would be to either:

    Use a boolean that will prevent old added objects to call the callback

    let newItems = false
    
    firebaseDb.child('invites').on('child_added', snapshot => {
      if (!newItems) { return }
      // do
    })
    
    firebaseDb.child('invites').once('value', () => {
      newItems = true
    })
    

    The disadvantage of this method is that it would imply getting events that will do nothing but still if you have a big initial list might be problematic.

    Or if you have a timestamp on your invites, do something like

    firebaseDb.child('invites')
      .orderByChild('timestamp')
      .startAt(Date.now())
      .on('child_added', snapshot => {
      // do
    })
    

提交回复
热议问题