How do I display the followers count in real time using firebase?

六眼飞鱼酱① 提交于 2020-01-07 08:23:27

问题


I have an application where users can follow other users. I want to have a real-time update system, display the total count of followers a user has.

I've just started playing around with Firebase and Pusher, but I don't understand one thing - will each user have their own 'channel'? How would I handle such thing as a follower counter update?

I followed the tutorial and saw that push method can create lists, so one solution I can see is having a list of all the users, each user being an object something like this:

{ username: 'john_doe', follower_count: 6 }

But I don't understand how would I actually track it on the front end? Should I have a filter, something like this?

var user = users.filter(function(user) { return user.username === 'john_doe'; });
// code to display user.follower_count

Or is there a different way that I'm missing?


回答1:


Most of Firebase logic is based on listeners, you can add a listener to events happening in your collections and when those events happen, you do something.

One way to go about this would be:

var myFollowerListRef = new Firebase(PATH_TO_YOUR_COLLECTION);
myFollowerListRef.on("value", function(snapshot) {
    console.log(snapshot.length);
});

This way, every time your follower collection changes, the asynchronous function fires and you can do what you want with the fresh data.

For more information:

https://www.firebase.com/docs/web/guide/retrieving-data.html

Hope this helps, I'm still a beginner in Firebase.




回答2:


@Th0rndike's approach is the simplest and works fine for relatively short lists. For longer lists, consider using a transaction. From the Firebase documentation on saving transactional data:

var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
  return (current_value || 0) + 1;
});

But I recommend that you read the entire Firebase guide. It contains solutions for a lot of common use-cases.



来源:https://stackoverflow.com/questions/36619647/how-do-i-display-the-followers-count-in-real-time-using-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!