【问题标题】:Guarantee the data retrieved from Firebase is not NULL保证从 Firebase 检索到的数据不为 NULL
【发布时间】:2021-08-16 07:16:24
【问题描述】:

我在尝试使用一些数据时遇到了这个错误:

未处理的拒绝 (TypeError):未定义不是对象(正在评估 'snapshot.docs[0].data')

我认为这是由于数据集是空的,尽管我是我组织的 Firebase 帐户的管理员。所以为了更健壮,我可以对我的代码做些什么?例如,如果检测到值undefined,如何设置默认值(即空字符串“”)?

import { AuthContext } from "./Auth/Auth";

function Transfer() {
    const [type, setType] = useState([]);
    const {currentUser} = useContext(AuthContext);

    useEffect(() => {
        if(currentUser){
            firebaseApp.firestore()
            .collection("User")
            .where("userEmail", "==", currentUser.email)
            .get()
            .then(snapshot => 
                setType(snapshot.docs[0].data().userType)
            );
        }
        

    }, [type])
}

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore firebase-authentication


    【解决方案1】:

    试试这个:

    const userInfo = snapshot.docs[0].data()
    setType(userInfo?.userType || "")
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2018-11-07
    • 1970-01-01
    相关资源
    最近更新 更多