我正在使用Firebase进行身份验证和存储。我正在使用react的useContext
将我的应用程序 Package 在身份验证层中。
一旦我从身份验证层获得用户,我就调用Firestore来检索用户的详细信息。但是,此函数正在循环。(多次调用)
export default function Profile() {
const { user, loading } = useContext(authContext);
const [profile, setProfile] = useState({});
const [dropdownOpen, setDropdownOpen] = useState(false);
const router = useRouter();
// THIS FUNCTION IS BEING LOOPED
const handleProfile = async () => {
const userProfileRef = doc(FIREBASE_FIRESTORE, "user", user.uid);
try {
const userProfile = await getDoc(userProfileRef);
setProfile(userProfile.data());
console.log("SET USER DATA");
} catch (error) {
console.log(error);
}
};
if (!user && !loading) {
router.push("/");
}
return (
<div className="flex flex-col relative">
{user &&
!loading &&
(handleProfile(),
(
<button
onClick={() => setDropdownOpen((prev) => !prev)}
className="flex items-center gap-2.5 focus:ring-0"
>
<Image
placeholder="blue"
alt="user profile"
src={profile.image_URL}
height={48}
width={48}
className="rounded-full bg-gray-400"
/>
<div className="flex flex-col text-left">
<p className="font-semibold">{profile.name}</p>
<p className="text-gray-400 text-sm">{profile.email}</p>
</div>
{dropdownOpen ? (
<FiChevronUp size={"20px"} color={"gray"} />
) : (
<FiChevronDown size={"20px"} color={"gray"} />
)}
</button>
))}
<div>{dropdownOpen && <UserDropdown />}</div>
</div>
);
}
任何帮助非常感谢。
1条答案
按热度按时间zaqlnxep1#
我建议将handleProfile移动到
useEffect
中,因为它只是从您的firestore获取数据:然后我还将删除JSX中的
handleProfile()
调用。如果你正在使用NextJS,我也建议你看看他们的data fetching解决方案(根据你的NextJS版本而有所不同)