首页 > 解决方案 > FirebaseError:使用无效数据调用的函数 addDoc()。不支持的字段值:未定义

问题描述

function Chat() {
    const [input, setInput] = useState("")
    const [seed, setSeed] = useState("")
    const {personid} = useParams()
    const [personname, setPersonname] = useState("")
    const [messages, setMessages] = useState([])
    const [{user}, dispatch] = useStateValue()

    useEffect(() => {
        if (personid) {
        db.collection("people")
        .doc(personid)
        .onSnapshot((snapshot) => 
            setPersonname(snapshot.data().name));

        db.collection("people")
        .doc(personid)
        .collection("messages")
        .orderBy("timestamp", "asc")
        .onSnapshot((snapshot) => 
            setMessages(snapshot.docs.map(doc =>doc.data()))
            )
        }
    }, [personid])

    useEffect(() => {
        setSeed(Math.floor(Math.random()*1000))
    }, [personid])

    const sendmessage = (e) => {
        e.preventDefault()
        console.log("The input is ", input);
        
        db.collection("people").doc(personid).collection("messages").add({
            message: input,
            name: user.displayName,
            timestamp: firebase.firestore.FieldValue.serverTimestamp(),
        })

        setInput("")
    }

在此处输入图像描述

当我尝试运行该功能时,出现下图中的错误。我曾尝试使用 google cloud firestore 的时间戳作为替代方案,但我不知道这是什么问题。

标签: javascriptreactjsfirebasereduxgoogle-cloud-firestore

解决方案


错误消息表明name您传递给该add()方法的对象的属性值未定义。

这个值是user.displayName并且,正如您将在doc中看到的,您应该“确保 Auth 对象在您获取当前用户时不处于中间状态(例如初始化)”。

为此,您可以使用onAuthStateChanged()观察者并将所需的业务逻辑放在一个if (user) {}块中,如文档中所示,或者,您firebase.auth().currentUser在执行user.displayName.


推荐阅读