0

I have this database

service/
-KSxobYDhjUJeSvu3dC1
 -Accion:"Nueva ronda"
 -Codigo: 3
 -dateTime: 1475284727
 -notify:  0
 -num_mesa: 0
-KSxobptdYSc-qrCSbyU
 -Accion: "Orden cancelada"
 -dateTime: 1475284728
 -notify: 0
 -num_mesa: 0

and then I have this code:

ref.orderByChild("notify").equalTo(1).limitToLast(1).on("child_added", function(snapshot) {
    var changedPost = snapshot.val();
    var mykey = snapshot.key;
    if(changedPost.notify == 1 ){
      var message = "New action "
      console.log(serviceArray[mykey].notify);//undefined
      $scope.showActionToast(message);
    } 
});

This code will read the last entry in the database and show a toast, notifying that a new action has been inserted in firebase. It shows the toast.

My problem is that I don't want it to show every time i reload the page.

So I thought about adding a simple flag that if it was shown in a toast, it will change notify to 0.

My problem is that I have service that returns a firebaseArray named serviceArray. When I try to access the row to change the value it says undefined. How can I change the value in the same function?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
2one2
  • 381
  • 2
  • 10
  • 23

2 Answers2

2

You're going to be better off simply tracking the timestamp of the last message you've shown to the user. With that you can query for messages that were added after that timestamp:

var timestampOfMostRecentlySeenMessage = null;
if (timestampOfMostRecentlySeenMessage) {
ref.orderByChild("timestamp")
   .startAt(timestampOfMostRecentlySeenMessage)
   .limitToLast(1)
   .on("child_added", function(snapshot) {
       var message = snapshot.val();
       timestampOfMostRecentlySeenMessage = message.dateTime;
   })

Now you just need to maintain the value of timestampOfMostRecentlySeenMessage between page reloads. You could do this in a cookie, in local storage of your browser or even in a user-specific part of your database:

var userRef = firebase.database().ref("users").child(user.uid);
userRef.child("timestampOfMostRecentlySeenMessage").set(timestampOfMostRecentlySeenMessage);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • the thing is that i want to push toast everytime theres a change in firebase, so i would need to update timestampOfMostRecentlySeenMessage too. my only problem is that the first time i load the page, i dont want to read the message. – 2one2 Oct 01 '16 at 02:49
0

i just added a flag that declares after running the search for the first time.

ref.orderByChild("notify").equalTo(1).limitToLast(1).on("child_added", function(snapshot) {
    var changedPost = snapshot.val();
    var mykey = snapshot.key;
    if(changedPost.notify == 1 && $scope.flag== 1 ){
      var message = "New action "
      console.log(serviceArray[mykey].notify);//undefined
      $scope.showActionToast(message);
    } 
   $scope.flag= 1; 

});
2one2
  • 381
  • 2
  • 10
  • 23