So I have this react and firebase blog app. I want to show the count of the post of every user on the account page, which should look like this:
My code looks like this:
const [user, loading] = useAuthState(auth);
const [posts, setPosts] = useState([])
const postRef = collection(db, "posts")
useEffect(() => {
if(user){
const userName = user.email
const getPost = async () => {
const q = query(postRef, where("author_email", "==", userName));
const data = await getDocs(q)
setPosts(data.docs.map((doc) => ({
...doc.data(),
id: doc.id
})));
};
getPost();
}}, []);
I imported following things:
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import React from 'react'
import { useAuthState } from 'react-firebase-hooks/auth'
import { faGoogle } from '@fortawesome/free-brands-svg-icons'
import { useState, useEffect } from 'react'
import { collection, getDocs, query, where } from 'firebase/firestore'
import { db } from '../firebase'
I am currently having an issue that it updates if I change the code, but not if I refresh the page.
The counter should be update realtime and always if I refresh
2
Answers
We don’t see in your code where you set a counter (maybe in the
setPosts()
function?) but it seems that you query all the posts of the user to get this count value. As a matter of fact you doconst q = query(postRef, where("author_email", "==", userName));
but nowhere in the corresponding app page we see the list of all the user’s posts, therefore I make the assumption that you use the length of the array you path to thesetPosts()
function.If you just want to display the number of user’s posts you should use a
count()
aggregation query which will be much cheaper than querying all the posts documents and faster as well.You have to display the size of post array in the tag where you have Your Post text.
Here is the sample:
use {posts.length} in the tag to show the count of posts he/she has.
But first you have to set the posts state by finding the posts of the logged in user.