简体   繁体   English

TypeError:无法读取 null 的属性(读取“uid”)

[英]TypeError: Cannot read properties of null (reading 'uid')

Hello Guys Hope everyone is doing well, i keep getting this error with my App, basically i am building a react chat app with firebase.大家好希望每个人都做得很好,我的应用程序一直出现这个错误,基本上我正在使用 firebase 构建一个反应聊天应用程序。 i tried everything i could so i hope someone here can help me if he/she could... the page is telling me that the error is at line 28 which is:我尽我所能,所以我希望有人能帮助我,如果他/她可以......页面告诉我错误在第 28 行,即:

const user1 = auth.currentUser.uid;

Here is my Home.js code这是我的 Home.js 代码

import React, { useEffect, useState } from "react";
import { db, auth, storage } from "../firebase";
import {
  collection,
  query,
  where,
  onSnapshot,
  addDoc,
  Timestamp,
  orderBy,
  setDoc,
  doc,
  getDoc,
  updateDoc,
} from "firebase/firestore";
import { ref, getDownloadURL, uploadBytes } from "firebase/storage";
import User from "../components/User";
import MessageForm from "../components/MessageForm";
import Message from "../components/Message";

const Home = () => {
  const [users, setUsers] = useState([]);
  const [chat, setChat] = useState("");
  const [text, setText] = useState("");
  const [img, setImg] = useState("");
  const [msgs, setMsgs] = useState([]);

const user1 = auth.currentUser.uid;

  useEffect(() => {
    const usersRef = collection(db, "users");
    // create query object
    const q = query(usersRef, where("uid", "not-in", [user1]));
    // execute query
    const unsub = onSnapshot(q, (querySnapshot) => {
      let users = [];
      querySnapshot.forEach((doc) => {
        users.push(doc.data());
      });
      setUsers(users);
    });
    return () => unsub();
  }, []);

  const selectUser = async (user) => {
    setChat(user);

    const user2 = user.uid;
    const id = user1 > user2 ? `${user1 + user2}` : `${user2 + user1}`;

    const msgsRef = collection(db, "messages", id, "chat");
    const q = query(msgsRef, orderBy("createdAt", "asc"));

    onSnapshot(q, (querySnapshot) => {
      let msgs = [];
      querySnapshot.forEach((doc) => {
        msgs.push(doc.data());
      });
      setMsgs(msgs);
    });

    // get last message b/w logged in user and selected user
    const docSnap = await getDoc(doc(db, "lastMsg", id));
    // if last message exists and message is from selected user
    if (docSnap.data() && docSnap.data().from !== user1) {
      // update last message doc, set unread to false
      await updateDoc(doc(db, "lastMsg", id), { unread: false });
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const user2 = chat.uid;

    const id = user1 > user2 ? `${user1 + user2}` : `${user2 + user1}`;

    let url;
    if (img) {
      const imgRef = ref(
        storage,
        `images/${new Date().getTime()} - ${img.name}`
      );
      const snap = await uploadBytes(imgRef, img);
      const dlUrl = await getDownloadURL(ref(storage, snap.ref.fullPath));
      url = dlUrl;
    }

    await addDoc(collection(db, "messages", id, "chat"), {
      text,
      from: user1,
      to: user2,
      createdAt: Timestamp.fromDate(new Date()),
      media: url || "",
    });

    await setDoc(doc(db, "lastMsg", id), {
      text,
      from: user1,
      to: user2,
      createdAt: Timestamp.fromDate(new Date()),
      media: url || "",
      unread: true,
    });

    setText("");
    setImg("");
  };
  return (
    <div className="home_container">
      <div className="users_container">
        {users.map((user) => (
          <User
            key={user.uid}
            user={user}
            selectUser={selectUser}
            user1={user1}
            chat={chat}
          />
        ))}
      </div>
      <div className="messages_container">
        {chat ? (
          <>
            <div className="messages_user">
              <h3>{chat.name}</h3>
            </div>
            <div className="messages">
              {msgs.length
                ? msgs.map((msg, i) => (
                    <Message key={i} msg={msg} user1={user1} />
                  ))
                : null}
            </div>
            <MessageForm
              handleSubmit={handleSubmit}
              text={text}
              setText={setText}
              setImg={setImg}
            />
          </>
        ) : (
          <h3 className="no_conv">Start A Conversation</h3>
        )}
      </div>
    </div>
  );
};

export default Home;

Try this add ternary condition to check till uid试试这个添加三元条件来检查直到 uid

 const user1 = auth?.currentUser?.uid;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的类型错误:无法读取 null 的属性(读取“uid”)。 试图获取 currentUser.uid - Uncaught TypeError: Cannot read properties of null (reading 'uid'). Trying to get the currentUser.uid typeerror cannot read properties of null reading uid,我没有异步代码和登录用户有什么想法? - typeerror cannot read properties of null reading uid, I have no asynchronous code and the users logged in any ideas? React 中的 Firestore 错误:未捕获(承诺)TypeError:无法读取 null 的属性(读取“uid”) - Firestore error within React: Uncaught (in promise) TypeError: Cannot read properties of null (reading 'uid') 未捕获(承诺)TypeError:无法读取 null 的属性(读取“用户”) - Uncaught (in promise) TypeError: Cannot read properties of null (reading 'users') 未捕获的类型错误:无法读取 null 的属性(读取“电子邮件”) - Uncaught TypeError: Cannot read properties of null (reading 'email') Firebase 类型错误:无法读取 null 的属性(读取“indexOf”) - Firebase TypeError: Cannot read properties of null (reading 'indexOf') TypeError:无法读取未定义的属性(读取“authService”) - TypeError: Cannot read properties of undefined (reading 'authService') 类型错误:无法读取未定义的属性(读取“缓冲区”) - TypeError: Cannot read properties of undefined (reading 'buffer') 无法读取 null 的属性(读取“电子邮件”) - Cannot read properties of null (reading 'email') 无法读取 null 的属性(读取“querySelector”) - Cannot read properties of null (reading 'querySelector')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM