Firebase trigger on all collection items while only one has been updated - javascript

Every time I do an update with the same object(s3) with same values and properties, Firebase trigger the event 'child_added' even if there's nothing to add or update.
I made some test by modifying on the firebase console some values in subcollection of the main object and noticed that it returns a snapshot with the first element correct and then all the other elements of the collections as 'ADDED' elements. This is not true because the collections didn't change except the one on which I performed an action.
I just need that when I send the same identical object that is stored on the db, firebase will recognize smartly that no action is requested and no trigger need to be activated.
var studentiRef = ref.child('studenti/' + s3.matricola);
studentiRef.update(JSON.parse(JSON.stringify(s3)));
studentiRef.on("child_changed", function(userSnapshot) {
var tasseRef = userSnapshot.ref.child('tasse');
tasseRef.on('child_added', function(itemSnapshot, prevKey){
console.log('ADDED ON');
console.log(itemSnapshot.key)
})
});
studentiRef.on("child_changed", function(userSnapshot) {
userSnapshot.ref.child('tasse').on('child_removed', function(itemSnapshot, prevKey){
console.log('REMOVED ON');
console.log(itemSnapshot.key)
})
});
studentiRef.on("child_changed", function(userSnapshot) {
userSnapshot.ref.child('tasse').on('child_changed', function(itemSnapshot, prevKey){
console.log('CHANGED ON');
console.log(itemSnapshot.key)
})
});
UPDATE:
Before posting update I made some experiments with no successful results.
Here the pics of the console, the database and the code.
Going nuts on this.
Here three screenshot: 1 firebase data 2 snippet 3 console log
UPDATE II:
scenario
behaviours on modifying value in firebase
SOLVED:
By getting inspired from the github firebase examples, I found out a common mistake in using firebase: i was not flatting the data.
To continue using my data structure (a root object within a list of objects), the solution was to trigger an update of every single object (pseudocode: ref.update(root/childobject) n-times instead of ref.update(root).
If someone else ran into this problem, I will explain better.
Always, FLAT YOUR DATA! (using firebase)

Most likely these events come directly from the client SDK, which doesn't detect if there was an actual change. The database server does perform such a check, and will only send out changes to other clients if there was an actual change.
Update:
The Firebase client + server behave in the following way when you're calling telling it to update a node to its current value.
The client fires the local event(s) to reflect the update. So child_changed will fire.
The client send the update to the server. This is needed since the client and server may be (slightly) out of sync, and the server is the single-source-of-truth.
The server compares the update with the current value of the node. If it is the same, the process stops here.
If the updated value is different from the current value and passes validation/permission checks, the data is committed to disk and broadcast to any active listeners.
If the updates value is different, but rejected by the validation/permission checks, the servers sends a rejection message to the original client, which then fires another child_changed event to revert the local change.

Related

How to only read changes in firebase realtime database

I have a database collection with readings, each new reading needs to be checked if it's out of the ordinary, if it is, there needs to be an alert sent.
So i'm using db.ref('collection').on('child_added', (child => { check(child); });
The problem with the .on function is that when the listener is added, all previous data is also read.
So how do i read a collection that only reads the changes in the database, also when the listener is first added? Or if that doesn't work, how do I differentiate the already added data with the new data?
The Firebase database synchronizes the state of whatever query or reference you attach your listener to. There is no option to only get new nodes built into the API.
If you want only new nodes, you will have to:
Ensure each node has an associated timestamp or order. If you're using Firebase's built-in push() keys, those might already serve that function.
Know what "new" means to the client, for example by either keeping the last timestamp or push key that it saw.
And then use a query to only request nodes after the stores timestamp/key.
So for example, if you only want to read nodes that are created after the moment you attach the listener, you could do something like this:
let now = db.ref('collection').push().key; // determine current key
db.ref('collection').orderByKey().startAt(now).on('child_added', ...)

Firebase on handler is always triggering

I’m using the following script:
var conversation = firebase.database().ref('conversations');
conversation.on('value', (snapshot) => {
const data = snapshot.val();
document.getElementById('#btn').click();
});
However, the on is always triggering even if there is no new data on the database. I know this because the button is always being pressed.
Does anyone knows what I’m doing wrong?
Thanks
This is the expected behavior. An on('value' listener immediately fires with a snapshot of the current value at that path in the database, and will fire again if any data under that path changes. Firebase synchronizes the state of the (paths you observe in the) database, it does not just pass messages around about changes as they happen (as a message queue would do).
If you want to get only new data, you should have some indication of what "new" means. For more on this, I recommend checking out some of the previous questions on only getting new data from Firebase.

Collection on client not changing on Meteor.subscribe with React

I am using Meteor with React JS.
I get the collection of "list" by this code,
Meteor.subscribe('getList', {status:'active'},function(){
self.setState({lists:Lists.find().fetch()});
});
Here is the code for publish,
Meteor.publish('getList', function(data){
data.user = this.userId;
return Lists.find(data);
});
So it is working. The problem is that I have two components that calling Meteor.subscribe('getList'). But the status is not the same.
So in other component, I have this code,
Meteor.subscribe('getList', {status:'archived'},function(){
self.setState({lists:Lists.find().fetch()});
});
So what happens here is, if the user go to FirstComponent, this.state.lists is empty (which is correct). Then when the user navigate to SecondComponent, this.state.lists is populated with data (which is correct). But when the user go back to FirstComponent, this.state.lists still populated with data (which is wrong).
It is like that the first collection (is empty) in client is still there. Then the second collection (not empty) is added. I want to clear the collection in client before subscribing again.
By the way I am using flow-router.
Since subscriptions are cumulative you should repeat the query condition in your setState functions:
let query = {status:'active'};
Meteor.subscribe('getList',query,function(){
self.setState({lists:Lists.find(query).fetch()});
});
query = {status:'archived'};
Meteor.subscribe('getList',query,function(){
self.setState({lists:Lists.find(query).fetch()});
});
Please note however that from a security perspective you really don't want to pass a query object from the (untrusted) client as a parameter to the subscription! From the console someone can just do:
Meteor.subscribe('getList',{});
It looks like you are setting the React state in the Meteor.subscribe onReady callback. Does each component have it's own state?
Where are you calling Meteor.subscribe from? Remember that Meteor puts subscription data in local mini-mongo and you are reading from there when you call Lists.find().
The way you have this set up, the data will not be reactive. You need to store handle to the Meteor.subscribe cursor and manage the subscription lifecycle with that.
If you could share more code, I could give a more concise answer.

How to prevent 'value' event on the client that issued set?

A Firebase client calling set() will cause all connected clients to have value triggered - including - the original client that issued the set().
In my case (and I think in most cases), there is no reason for the client that issued the set() to respond to the value event produced by its own call. Obviously its model is correct and there's no need to change it (which may be an expensive operation).
Is there any way for the client to not-receive/prevent/ignore the value event triggered by its own set() call ? I considered using off/on around set() but that can make the client miss value events that came at the same time but were not triggered by it.
Am I missing something obvious ?
Most applications treat the Firebase data itself as their model. So when there's an update, they call ref.set() (or another mutator function) and then the update flows back into their app through an on() event. React/Flux aficionados know this as a unidirectional data-flow, other might know it as Command Query Responsibility Segregation.
But there indeed cases where the model has already been updated and thus you want to ignore the event from Firebase if you're the one who triggered it.
There is no API for not receiving theses self-triggered events. Instead you'll have to "remember" the data that you sent to Firebase and filter it out in your on() handler.
The Android drawing sample from Firebase keeps a list of segments that it sends to Firebase and then ignores those segments in its onChildAdded handler. It uses push ids to identify the line segments and those are generated client-side, so it can use those to track identify the segments.
A JavaScript sample of this:
var pendingChildIds = []; // Push ids of nodes we've sent to the server, but haven't received in `on()` yet
// this code is in your UI event handler, or whatever triggers the needs to update your Firebase data
var newChild = ref.push();
pendingChildIds.push(newChild.key());
newChild.set(
{ property1: 'value1', property2: 3.14 },
function(error) {
// the write operation has completed, remove the child id from the list of pending writes
pendingChildIds.splice(pendingChildIds.indexOf(newChild.key());
}
);
// this is the event handler, using child_added in this case
ref.on('child_added', function(snapshot) {
if (!pendingChildIds.contains(snapshot.key())) {
// this is a child that we DIDN'T generate
}
});
I ended up adding a client ID to the model, something like:
var clientId=(Math.random()*10000000000000000).toFixed(0);
function set(data) {
ref.set(JSON.stringify({ clientId: clientId, data: data }));
}
ref.on('value', function(snapshot) {
var json=JSON.parse(snapshot.val());
if (!json || json.clientId===clientId) return;
var data=json.data;
// update model with data
});

How to unsubscribe from the collection?

My publications:
Meteor.publish('items', function() {
return Items.find({}, {skip: randomNumber, limit: 100});
});
My subscription code happening when a button is clicked (in templates.event)
Meteor.subscribe('items');
Items.find().fetch();
However, the problem is that items isn't refreshed with the new data, but new data is appended to the old list instead. What can I do to unsubscribe the old data?
When you call Meteor.subscribe it will return a subscription handle.
You call stop on the handle to cancel it.
eg, in your event helper
if (SomeGlobalVar){
SomeGlobalVar.stop();
}
SomeGlobalVar = Meteor.subscribe('items');
The other way is to run the subscription inside Deps.autorun; it will automatically clean up old subscriptions.
eg, in you event handler
Session.set('subscribe', true);
Elsewhere in your code:
Deps.autorun(function(){
if (Session.get('subscribe')){
Meteor.subscribe('items');
}
});
If you call Session.set('subsribe', false); Meteor will automatically cancel/clean-up that subscription to items.
Seems to me like there is a bit of a confusion here, when you are connecting to a reactive data source you are not subscribing to specific data, so when new records are added ofcourse they are appended to your data through that connection.
If I understood your question and you want the new data to completely replace the old data I advise you not to build your template around the Collection but rather build it around a cached version of the data (which will kept in an object and made reactive using Deps), that way you will have total control over the data displayed.

Categories