32

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,

Dalin Huang
  • 11,212
  • 5
  • 32
  • 49
Lee
  • 5,816
  • 6
  • 45
  • 61
  • only when the listener triggered for first time, child_added will trigger for number of child children in that node,after that it will trigger only when new child is added. – Priya Apr 17 '17 at 06:53
  • I know, thats what i mentioned in my question.. I only want new items... – Lee Apr 17 '17 at 18:04

5 Answers5

29

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
})
Preview
  • 35,317
  • 10
  • 92
  • 112
  • 1
    Don't forget to take the time difference between the server and client into account when using timestamps. Take a look at [Clock skew](https://firebase.google.com/docs/database/web/offline-capabilities#clock-skew) in the docs. Once the serverTimeOffset has been retrieved it can easily be added like `.startAt(Date.now() + serverTimeOffset)`. – BillyNate May 31 '18 at 21:23
23

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

Preview
  • 35,317
  • 10
  • 92
  • 112
Lee
  • 5,816
  • 6
  • 45
  • 61
  • 1
    limitToLast(1) promisses to last added item ok. but what will happened if there is more than 1 records added before you delegation. it will lost them except last 1. wrong answer i think. right? – Nuri YILMAZ Oct 11 '18 at 13:48
  • This didn't work for me. Added children don't trigger any event. – Pedro Madrid Dec 07 '18 at 15:32
2

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 })
Matt Way
  • 32,319
  • 10
  • 79
  • 85
0

there was also another solution: get the number of children and extract that value: and it's working.

var ref = firebaseDb.child('invites')
ref.once('value').then((dataSnapshot) => {
        return dataSnapshot.numChildren()
    }).then((count) =>{
        ref .on('child_added', (child) => {
            if(count>0){
                count--
                return
            }
            console.log("child really added")
          });
     });
0

If your document keys are time based (unix epoch, ISO8601 or the firebase 'push' keys), this approach, similar to the second approach @balthazar proposed, worked well for us:

const maxDataPoints = 100; 
const ref = firebase.database().ref("someKey").orderByKey();
// load the initial data, up to whatever max rows we want
const initialData = await ref.limitToLast(maxDataPoints).once("value")
// get the last key of the data we retrieved
const lastDataPoint = initialDataTimebasedKeys.length > 0 ? initialDataTimebasedKeys[initialDataTimebasedKeys.length - 1].toString() : "0"
// start listening for additions past this point...
// this works because we're fetching ordered by key
// and the key is timebased
const subscriptionRef = ref.startAt(lastDataPoint + "0");
const listener = subscriptionRef.on("child_added", async (snapshot) => {
    // do something here
});
James Crowley
  • 3,911
  • 5
  • 36
  • 65