Answer a question

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("")
    }

enter image description here

I get the error in the picture below when I try to run that function. I have tried using google cloud firestore's timestamp as an alternative but I don't know what the problem with this is.

Answers

The error message indicates that the value of the name property of the object you pass to the add() method is undefined.

This value is user.displayName and, as you will see in the doc, you should "ensure that the Auth object isn't in an intermediate state —such as initialization— when you get the current user".

For that, either you use the onAuthStateChanged() observer and put the desired business logic in a if (user) {} block, as shown in the doc, OR, you manually check that firebase.auth().currentUser is not null before doing user.displayName.

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐