[英]React useEffect is returning empty data when page loads for the first time
[英]useEffect with firebase and nextjs undefined when page first loads
我有一個從 firestore 拉入子集合的組件:
import { useEffect, useState } from "react";
import { db } from '../firebase/firebaseInit'
import {useAuth} from '../components/AuthContextProvider'
import { collection, getDocs, setDoc, doc, addDoc } from "firebase/firestore";
type Inputs = {
name: string,
gender: string,
date: any,
}
function Subscriptions({ Component, pageProps }: any) {
const { user } = useAuth()
const [kids, setKids] = useState<any>([])
useEffect(() => {
const getKids = async (user: any) => {
if (user) {
const KidsCollectionRef = collection(doc(collection(db, "users"), user.uid), "kids")
const data = await getDocs(KidsCollectionRef)
setKids(data.docs.map((doc) => ({
...doc.data(), id: doc.id
})))
console.log(kids)
}
}
getKids(user)
}, [])
return (
<>
<h1>Welcome back</h1>
{/* need to loop throug the different prices */}
<div>
{kids.map((kid, index) => (
<span key={index} style={{display: 'block', width: '100%'}}>
{kid.name}
</span>
))}
</div>
</>
)
}
export default Subscriptions
但是,如果我將useEffect
更改為此,它只會 console.logs 來自kids
的數據:
useEffect(() => {
const getKids = async (user: any) => {
if (user) {
const KidsCollectionRef = collection(doc(collection(db, "users"), user.uid), "kids")
const data = await getDocs(KidsCollectionRef)
setKids(data.docs.map((doc) => ({
...doc.data(), id: doc.id
})))
console.log(kids)
}
}
getKids(user)
}, [kids])
這並不理想,因為它會導致無限循環。
這是console.logs:
從firestore獲取數據時如何進行useEffect更新?
只需將user.uid
添加到 useEffect dep,uid 不會改變,但它可以是未定義的或值,這意味着它只會在值上觸發
useEffect(() => {
const getKids = async () => {
if (user) {
const KidsCollectionRef = collection(doc(collection(db, "users"), user.uid), "kids")
const data = await getDocs(KidsCollectionRef)
setKids(data.docs.map((doc) => ({
...doc.data(), id: doc.id
})))
console.log(kids)
}
}
getKids()
}, [user?.uid])
如果您想查看新的孩子,您可以在 setKids 中更改 state 之前這樣做。
useEffect(() => {
//...
setKids(() => {
const newState = data.docs.map((doc) => ({...doc.data(), id: doc.id}))
console.log(newState);
return newState;
})
}, [])
或者只是添加另一個 useEffect
// useEffect with fetch
useEffect(() => { //... }, [])
// useEffect with log
useEffect(() => {
console.log(kids)
}, [kids])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.