简体   繁体   English

首次加载页面时未定义 firebase 和 nextjs 的 useEffect

[英]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.

相关问题 第一次加载页面时,React useEffect 返回空数据 - React useEffect is returning empty data when page loads for the first time 第一次加载页面时,React useEffect 返回空数据数组 - React useEffect is returning empty data array when page loads for the first time 当我尝试使用 useEffect 将信息从 firebase 获取到 nextjs 时出现无限循环 - Infinity loop when I try to get information from firebase into nextjs using useEffect Firestore 查询在页面首次加载时没有得到结果,但在页面重新呈现时 - React Native - Firestore query not getting results when page first loads, but is when page re-renders - React Native React-Firebase:为什么页面在第一次加载时失败,但在刷新时加载正确? - React-Firebase: Why does page fail on first load, but then loads properly on refresh? Firebase查询function页面刷新时返回undefined - Firebase query function returning undefined when page is refreshed 首次使用 navigation.navigate 加载页面时未获取 currentUser.uid - Not getting currentUser.uid when the page first loads using navigation.navigate 刷新页面时 useEffect 不需要的副作用 - useEffect unwanted side effect when refresh page UseEffect 无限循环与 Firebase - UseEffect infinite loop with Firebase 如何使用 useEffect 将 firebase 实时数据库中的更改显示到我的页面? - How can I show the change in firebase realtime database to my page with useEffect?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM