Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase child_added for new items only

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,

like image 479
Lee Avatar asked Apr 16 '17 18:04

Lee


People also ask

How do I get particular data from Firebase?

You do that like this: // Get a reference to your user final FirebaseDatabase database = FirebaseDatabase. getInstance(); DatabaseReference ref = database. getReference("server/path/to/profile"); // Attach a listener to read the data at your profile reference ref.

Does Firebase scale automatically?

Lastly, it'll scale massively and automatically. Firebase Functions will just do it automatically for you based on the traffic you receive and at an incredibly low cost.


2 Answers

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 }) 
like image 98
Preview Avatar answered Sep 25 '22 19:09

Preview


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

like image 41
Lee Avatar answered Sep 23 '22 19:09

Lee