我創建了這個自定義掛鉤來獲取(在本例中為收聽)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;
問題是:isUserLoading總是回傳false,即使在try宣告中,我將其設定為true
知道為什么會這樣嗎?
uj5u.com熱心網友回復:
onSnapshot回傳一個函式,而不是一個承諾,所以你不能await
所以你想要做的是:
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
}, []);
在您當前的代碼中,finally將立即運行,因為沒有什么可等待的
uj5u.com熱心網友回復:
來自 w3schools.com:
try 陳述句定義要運行(嘗試)的代碼塊。
catch 陳述句定義了一個代碼塊來處理任何錯誤。
finally 陳述句定義了一個代碼塊,無論結果如何都要運行。
因此,您將其設定為truein,try然后將其設定回falseright after。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533609.html
標籤:Google Cloud Collective 反应火力基地
