[英]How do I fix this section of code to allow the user to get their favorites from Firebase Realtime db? even with uid working, user can't view favorites
這是返回的錯誤消息:TypeError:無法讀取 null 的屬性 'uid'
這是我需要幫助的來自 FavoritesContext.jsx 組件的代碼部分:
useEffect(() => {
const uid = firebase.auth().currentUser.uid;
if (!uid) {
return;
} else
db.ref(`users/${uid}/favorites`).on("value", (snapshot) => {
console.log("favorites: ", snapshot.toJSON());
const results = Object.entries(snapshot.toJSON() || {}).map(
([id, props]) => ({
id,
...props,
})
);
setFavorites(results);
});
}, []);
這是 db 在我的 Base.js 組件中的來源:
export const db = firebase.database(uiConfig);
這是我的 AuthContext.js 組件中的相關代碼:
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const [pending, setPending] = useState(true);
useEffect(() => {
app.auth().onAuthStateChanged((user) => {
setCurrentUser(user);
setPending(false);
});
}, []);
來自 firebase 官方文檔
您還可以使用 currentUser 屬性獲取當前登錄的用戶。 如果用戶未登錄,則 currentUser 為空:
你得到 uid null 因為你的用戶還沒有登錄。
你可以在這里閱讀更多
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.