[英]React custom hook to fetch document from firebase isLoading always false
I created this custom hook to fetch (in this case listen to) a document in firestore:我创建了这个自定义挂钩来获取(在本例中为监听)firestore 中的文档:
import { doc, onSnapshot } from 'firebase/firestore';
import { useEffect, useState } from 'react';
import { db, auth } from '../../firebase';
function useCurrentUser() {
const userId = auth.currentUser.uid;
const [user, setUser] = useState({});
const [isUserLoading, setIsUserLoading] = useState(false);
const [isUserError, setIsUserError] = useState(null);
useEffect(() => {
const getUser = async () => {
try {
setIsUserLoading(true);
const userRef = doc(db, 'users', userId);
const unsub = await onSnapshot(userRef, doc => {
setUser(doc.data());
});
} catch (error) {
setIsUserError(error);
} finally {
setIsUserLoading(false);
}
};
getUser();
}, []);
return { user, isUserLoading, isUserError };
}
export default useCurrentUser;
The problem is: isUserLoading
is always returning false
even though in the try
statement, I'm setting it to true
问题是:
isUserLoading
总是返回false
,即使在try
语句中,我将其设置为true
Any idea why this is happening?知道为什么会这样吗?
onSnapshot
returns a function, not a promise, so you can't await
onSnapshot
返回 function,而不是 promise,所以你不能await
So what you want to do is:所以你想要做的是:
useEffect(() => {
setIsUserLoading(true);
const userRef = doc(db, 'users', userId);
const unsub = onSnapshot(userRef, snapshot => {
if(!snapshot.exists()) return
setIsUserLoading(false);
setUser(snapshot.data());
});
return unsub
}, []);
In your current code, finally
would run immediately, because there is nothing to await for在您当前的代码中,
finally
会立即运行,因为没有什么可等待的
From w3schools.com:来自 w3schools.com:
The try statement defines the code block to run (to try).
try 语句定义要运行(尝试)的代码块。
The catch statement defines a code block to handle any error.
catch 语句定义了一个代码块来处理任何错误。
The finally statement defines a code block to run regardless of the result.
finally 语句定义了一个代码块,无论结果如何都要运行。
So you're setting it to true
in the try
then setting it back to false
right after.因此,您在
try
中将其设置为true
,然后立即将其设置回false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.