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,
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.
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.
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 })
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With