0👍
I’ll assume you use firestore and have a ‘posts’ collection where you save individual posts. You could save a ‘views’ counter in each post and increment its value every time someone clicks the button you describe.
If you get the post data when the button is clicked, you can increment the ‘views’ counter before or after (depending on what you want) retrieving the post document from firestore.
You can do all that with the firebase sdk or using a callable function.
Now, this gives you the behavior you described, which might be what you want if there won’t be that many post reads. However, you should consider that this solution:
- Gives you the exact number of times a post has been requested.
- Adds a write operation that you will be charged for (beyond the free tier) every time someone wants to view a post.
So, if you expect every post to be read a lot and, in that case, if you don’t really care about the exact number of views (e.g. if a post has 1,045,154 views, you might just want to display 1M views), and if you care about how much you will be billed (i.e. reduce writes), you could :
- Increment the ‘views’ counter less frequently with something like this:
if(getRandomNumber(0, 100) == 100){
// Increment the 'views' counter by 100 units
}
This would increment the counter by 100 roughly every 100 post reads, and give you an approximation of how many times a post has been viewed. You can adjust it to reduce frequency. This saves you writes, but costs you precision.
- Increment the ‘views’ counter based on a certain condition (e.g. a user has seen 80%+ the post) rather than every time someone clicks on the button to view the post. This could make writes less frequent, and maybe even make the counter more accurate depending on how you define a user viewing a post, but adds complexity.
Remember that these are just suggestions and whether you should consider them or not depends on your particular case 👍🏼.
- [Vuejs]-How to update a textarea with vue.js based on single inputs from textarea
- [Vuejs]-Laravel blade template and VueJs combination