K.Wu
K.Wu

Reputation: 3633

How to get the most recent data from firebase database?

Suppose I am writing a Twitter clone (but much simpler) with firebase database. A post contains only the message body. In the database, besides the message body, I also keep track of these things:

enter image description here

where likeCount is the number of likes on the post. It's incremented whenever someone likes the post. Posts are downloaded via Cloud Functions, because pagination is used and 10 posts are downloaded at a time. So, my question is, at the time of download, suppose each post has only 1 like, but if someone else likes a post, therefore, there should be 2 likes on the post now, how to I get this most recent likeCount without having to refresh the page?

Upvotes: 0

Views: 669

Answers (1)

Basavannevva
Basavannevva

Reputation: 294

In Android you should do like this to get the Updates of likeCount node

FirebaseDatabase database;
String postId="KyELxNpEaRt2Y64flUn"

database.getReference().child("posts/" + postId + "/likeCount").onChildChanged(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) 
{
if (dataSnapshot.getValue() != null) {
//here you should update the value
}
})
})

In React Native

 postRef=`/posts/${postId}/likeCount`;
 firebase.database().ref(postRef).on("child_changed", snap => {
    if (snap.val() != null) {
     //here you shold update the value
    }
  });

Upvotes: 4

Related Questions