1

When my application starts I do an initial fetch to Firebase to pull down all my data. When I later add data to my Firebase, I only want it to get the new child that's been added.

I'm currently achieving this like this. Is there a better way, or a built in way to do this in Firebase?

let initialFetch = false;

ref.once('value', snap => {
  // get all child data
  initialFetch = true;  
});

ref.on('child_added', (snap) => {
  if (!initialFetch) return;
  // get new child data
});

Any help is appreciated. Thanks in advance!

realph
  • 4,481
  • 13
  • 49
  • 104

1 Answers1

2
  1. If you need both new data and subsequent data, use child_added. It will fire immediately for all existing children and subsequently for any child that is added.

  2. if you only want new data, add a timestamp to your children and ref.orderByChild('timestamp').startAt(Date.now())

  3. If you need both new data and subsequent data, but want to treat the initial children differently: use child_added and value as you do now.

Also see: How to only get new data without existing data from a Firebase?

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I'd love to use option 1 (`child_added`), but I need to fetch some more metadata from another api once I get back my initial data from Firebase. Does `.on()` support promises? – realph Sep 17 '16 at 18:17
  • A promise can only resolve once. Firebase's `on()` will trigger every time the relevant event occurs, so cannot return a promise. If you only care about a single value, use `once()` (which returns a promise). – Frank van Puffelen Sep 18 '16 at 02:21