帖子计数在Firebase React中未更新。

huangapple go评论89阅读模式
英文:

Post Count not updating in firebase react

问题

我目前有一个React和Firebase博客应用程序。我想在账户页面上显示每个用户的帖子数量,应该看起来像这样:帖子计数在Firebase React中未更新。

我的代码如下:

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';

const style = {
  button: 'font-bold text-3xl text-white bg-slate-500 p-4 rounded',
  info: 'font-bold',
};

const Account = ({ auth, handleSignIn, handleSignOut }) => {
  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();
    }
  }, []);

  return (
    <div className='text-center p-4'>
      {loading ? (
        <div>
          <p className='italic'>正在获取用户数据...</p>
        </div>
      ) : user ? (
        <div>
          <div className='m-4'>
            <p>你的名字<span className={style.info}>{user.displayName}</span></p>
            <p>你的电子邮件<span className={style.info}>{user.email}</span></p>
            <p>你的帖子数量<span className={style.info}>{posts.length}</span></p>
          </div>
          <button onClick={handleSignOut} className={style.button}>退出登录</button>
        </div>
      ) : (
        <div>
          <button onClick={handleSignIn} className={style.button}>使用 <FontAwesomeIcon icon={faGoogle} /> 登录</button>
        </div>
      )}
    </div>
  );
};

export default Account;

我目前遇到的问题是,如果我更改代码,它会更新,但如果我刷新页面,它不会更新。

计数器应该实时更新,即使我刷新页面也应该更新。

英文:

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:帖子计数在Firebase React中未更新。

My code looks like this:

import { FontAwesomeIcon } from &#39;@fortawesome/react-fontawesome&#39;
import React from &#39;react&#39;
import { useAuthState } from &#39;react-firebase-hooks/auth&#39;
import { faGoogle } from &#39;@fortawesome/free-brands-svg-icons&#39;
import { useState, useEffect } from &#39;react&#39;
import { collection, getDocs, query, where } from &#39;firebase/firestore&#39;
import { db } from &#39;../firebase&#39;
const style = {
button: `font-bold text-3xl text-white bg-slate-500 p-4 rounded`,
info: `font-bold`
}
const Account = ({ auth, handleSignIn, handleSignOut }) =&gt; {
const [user, loading] = useAuthState(auth);
const [posts, setPosts] = useState([])
const postRef = collection(db, &quot;posts&quot;)
useEffect(() =&gt; {
if(user){
const userName = user.email
const getPost = async () =&gt; {
const q = query(postRef, where(&quot;author_email&quot;, &quot;==&quot;, userName));
const data = await getDocs(q)
setPosts(data.docs.map((doc) =&gt; ({
...doc.data(),
id: doc.id
})));
};
getPost();
}}, []);
return (
&lt;div className=&#39;text-center p-4&#39;&gt;
{loading ? 
&lt;div&gt;
&lt;p className=&#39;italic&#39;&gt;Fetching user data ...&lt;/p&gt;
&lt;/div&gt;
: user ?
&lt;div&gt;
&lt;div className=&#39;m-4&#39;&gt;
&lt;p&gt;Your Name: &lt;span className={style.info}&gt;{user.displayName}&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Your Email: &lt;span className={style.info}&gt;{user.email}&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Your Posts: &lt;span className={style.info}&gt;{posts.length}&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;button onClick={handleSignOut} className={style.button}&gt;Sign Out&lt;/button&gt;
&lt;/div&gt;
:
&lt;div&gt;
&lt;button onClick={handleSignIn} className={style.button}&gt;Sign in with &lt;FontAwesomeIcon icon={faGoogle} /&gt;&lt;/button&gt;
&lt;/div&gt;
}
&lt;/div&gt;
)
}
export default Account

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

答案1

得分: 0

我们在您的代码中没有看到您设置计数器的地方(也许在setPosts()函数中?),但似乎您查询了用户的所有帖子以获取此计数值。事实上,您执行了const q = query(postRef, where("author_email", "==", userName));,但在相应的应用页面中,我们没有看到用户所有帖子的列表,因此我假设您使用了传递给setPosts()函数的数组的长度来进行计数。

如果您只想显示用户的帖子数量,您应该使用count()聚合查询,这将比查询所有帖子文档便宜得多,而且速度更快。

英文:

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 do const q = query(postRef, where(&quot;author_email&quot;, &quot;==&quot;, 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 the setPosts() 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.

答案2

得分: 0

你必须在标签中显示帖子数组的大小,该标签上有“Your Post”文本。

这是一个示例:

在标签中使用**{posts.length}**来显示他/她拥有的帖子数量。

但首先,你必须通过查找已登录用户的帖子来设置帖子状态。

由于我们知道useState是异步的,所以你还必须使用某种加载器/旋转器。

英文:

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.

As we know that useState is async in nature so, you also have to use some kind of loader/spinner.

答案3

得分: 0

useEffect()的结尾,我必须将user传递到方括号中。

英文:

It was actually a little thing: at the end of the useEffect() I had to pass in user into the square brackets

huangapple
  • 本文由 发表于 2023年6月19日 20:41:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76506725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定