1
votes
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.

1
First off, I don't see the code that actually calls addDoc. but my guess would be on line 48 when you call .doc(personid), perhaps personid is undefined? Check the value, and the docs for that method to see if you're using it correctly - Lucas
I didn't write the code that calls addDoc and that's why I'm confused. Also personid isn't undefined because it worked perfectly fine before adding lines 16-23. - Priyadarsh S S
Please add the error message as text in your question, in such a way others can find it through search engines. - Renaud Tarnec
I will definitely do that next time. The error was with user.displayName . Thank you. - Priyadarsh S S

1 Answers

1
votes

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.