Firebase child_added for new items only

11,109

Solution 1

I have solved the problem using the following method.

firebaseDb.child('invites').limitToLast(1).on('child_added', cb)
firebaseDb.child('invites').on('child_changed', cb)

limitToLast(1) gets the last child object of invites, and then listens for any new ones, passing a snapshot object to the cb callback.

child_changed listens for any child update to invites, passing a snapshot to the cb

Solution 2

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
})

Solution 3

I solved this by ignoring child_added all together, and using just child_changed. The way I did this was to perform an update() on any items i needed to handle after pushing them to the database. This solution will depend on your needs, but one example is to update a timestamp key whenever you want the event triggered. For example:

var newObj = { ... }
// push the new item with no events
fb.push(newObj)
// update a timestamp key on the item to trigger child_changed
fb.update({ updated: yourTimeStamp })
Share:
11,109
Lee
Author by

Lee

Updated on July 07, 2022

Comments

  • Lee
    Lee almost 2 years

    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 => {
    })
    

    The idea behind this method is that we get a payload from the database and only use one action to updated my local data stores via the Reducers.

    Next, I need to listen for any NEW or UPDATED children of the key invite. The problem now, however, is that the child_added event triggers for all existing keys, as well as newly added ones. I do not want this behaviour, I only require new keys, as I have the existing data retrieved.

    I am aware that child_added is typically used for this type of operation, however, i wish to reduce the number of actions fired, and renders triggered as a result.

    What would be the best pattern to achieve this goal?

    Thanks,