[英]useEffect with firebase and nextjs undefined when page first loads
I have a component that pulls in a subcollection from firestore:我有一个从 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
But it only console.logs the data from kids
if I change useEffect
to this:但是,如果我将
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])
Which isn't ideal as it causes an infinite loop.这并不理想,因为它会导致无限循环。
Here's the console.logs:这是console.logs:
How do I make useEffect update when it gets the data from firestore?从firestore获取数据时如何进行useEffect更新?
Just add user.uid
to useEffect dep, uid doesn't change, but it can be either undefined or a value, meaning it will trigger on value only只需将
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])
If you want to look at new kids, you can do so before the change state, in setKids.如果您想查看新的孩子,您可以在 setKids 中更改 state 之前这样做。
useEffect(() => {
//...
setKids(() => {
const newState = data.docs.map((doc) => ({...doc.data(), id: doc.id}))
console.log(newState);
return newState;
})
}, [])
Or just add another useEffect或者只是添加另一个 useEffect
// useEffect with fetch
useEffect(() => { //... }, [])
// useEffect with log
useEffect(() => {
console.log(kids)
}, [kids])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.