[英]TypeError: currentUser is null in firebase react
I found different already answered questions to my question, but the don't help.我发现我的问题已经回答了不同的问题,但没有帮助。
I use a custom context to call the firebase.auth().onAuthStateChanged()
and set the currentUser
.我使用自定义上下文调用firebase.auth().onAuthStateChanged()
并设置currentUser
。
import React, { useState, useEffect } from "react";
import app from "../firebase";
export const AuthContext = React.createContext();
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
useEffect(() => {
app.auth().onAuthStateChanged(setCurrentUser);
}, []);
return (
<AuthContext.Provider value={{ currentUser }}>
{children}
</AuthContext.Provider>
);
};
In my component I call the AuthContext
and the currentUser
:在我的组件中,我调用AuthContext
和currentUser
:
import React, { useContext, useEffect, useState } from "react";
import app from "./firebase";
import { AuthContext } from "./Auth/Auth";
function MyComponent() {
const [invoices, setInvoices] = useState([]);
const { currentUser } = useContext(AuthContext);
const getInvoices = () => {
const database = app.firestore();
const unsubscribe = database
.collection("invoices")
.where("uid", "==", currentUser.uid) // HERE currentUser IS NULL
.orderBy("date", "desc")
.onSnapshot((snapshot) => {
setInvoices(
snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }))
);
});
return () => {
unsubscribe();
};
};
useEffect(() => {
getInvoices();
}, []);
return (<> ... </>);
}
export default MyComponent;
I believe my issue has something to do with promises and the user is not yet loaded.我相信我的问题与承诺有关,并且用户尚未加载。 But still I don't know what to do here.但我仍然不知道在这里做什么。
The potential issue could be the value of currentUser
returns a bit later so you need to add an extra check in your MyComponent
component.潜在的问题可能是currentUser
的值稍后返回,因此您需要在MyComponent
组件中添加额外的检查。
I would add null
check for currentUser
and extend the dependency array as:我会添加null
检查currentUser
并将依赖项数组扩展为:
useEffect(() => {
if (currentUser) {
getInvoices();
}
}, [currentUser]);
Probably in the first round the useEffect
callback was running once currentUser
was still null
.可能在第一轮中,一旦currentUser
仍然是null
, useEffect
回调就会运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.