简体   繁体   中英

TypeError: Cannot read property 'name' of undefined error using firebase

I am getting the following error when I am trying to run my app

TypeError: Cannot read property 'name' of undefined

 26 | 
  27 |  useEffect(() => {
  28 |    if (roomId) {
> 29 |      db.collection("rooms")
     | ^  30 |        .doc(roomId)
  31 |        .onSnapshot((snapshot) => setRoomName(snapshot.data().name));
  32 | 

I have already defined the rooms/messages & names in my firestore. I have imported the firebase.js file & added the firebase config as well. Here is the piece of code in my js file from where it is throwing error.

import db, { auth, provider } from "./firebase";
import firebase from "firebase";
import React, { useState, useEffect } from "react";

.... code ...
function Chat() {

  const { roomId } = useParams();
  const [roomName, setRoomName] = useState("");
  const [messages, setMessages] = useState([]);
  const [{ user }, dispatch] = useStateValue();


  useEffect(() => {
    if (roomId) {
      db.collection("rooms")
        .doc(roomId)
        .onSnapshot((snapshot) => setRoomName(snapshot.data().name));

    }
  }, [roomId]);

Any help is very much appreciated.

Edit: This is the data base structure: 图片1

图像2

The error is telling you that snapshot.data() returned undefined. This can happen if there is no document at the location you queried (/rooms/{roomId}). You should check for this case before you access properties on an object that doesn't exist.

.onSnapshot((snapshot) => {
    const data = snapshot.data();
    if (data) {
        setRoomName(data.name));
    }
    else {
        // decide what you want to do if there is no document
    }
}

Since we can't see your database, nor can we see the value of roomId , we can't say why this is happening - you will have to debug your code and data to figure that out.

Instead of using onSnapshot, try using get method

const getRoom = useCallback(async roomId => {
    if (roomId) {
      const room = await db.collection("rooms")
        .doc(roomId)
        .get();
      setRoomName(room.data().name);
    }
    setRoomName(null);
}, [])

useEffect(() => {
  getRoom(roomId)
}, [getRoom]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM