简体   繁体   English

在 React 中访问 firebase 文档之前等待 UserID

[英]Wait for UserID before accessing firebase documents in react

After a user signs in to my program, they get redirected to a page where their profile data is fetched, however I need to wait on the page for the current user to not be null before reading the data from firebase.用户登录到我的程序后,他们会被重定向到获取其个人资料数据的页面,但是我需要在页面上等待当前用户不是 null,然后才能从 firebase 读取数据。

Inside user page:内部用户页面:

  const currentUser = useAuth();
  const routineBundleRef = doc(db, "RoutineBundle", currentUser.uid);

  useEffect(() => {
    const getRoutines = async () => {
      const data = await getDocs(collection(routineBundleRef, "Routines"));
      setRoutines(data.docs.map((doc) => ({...doc.data(), id: doc.id})));
    };
    getRoutines();
  }, []);

Inside auth page:内部授权页面:

const useAuth = () => {
  const [currentUser, setCurrentUser] = useState();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, user => { setCurrentUser(user)});
    return unsub;
  }, [])

  return currentUser;
}

The page is being accessed with a userid, but I think the problem is that it does not load in time before trying to access user documents.该页面正在使用用户标识访问,但我认为问题在于它在尝试访问用户文档之前没有及时加载。

How would I go about waiting for usedid, before accessing documents?请问我go怎么等待usedid,才可以访问文件?

无 ID 错误消息图片

Thanks for any help.谢谢你的帮助。

The user in onAuthStateChanged can be null . onAuthStateChanged中的user可以是null Try adding an if statement to check that:尝试添加一个if语句来检查:

useEffect(() => {
  const unsub = onAuthStateChanged(auth, user => {
      if (user) {
        setCurrentUser(user)
      });
  }
  return unsub;
}, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM