首页 > 解决方案 > 嗨,我正在尝试使用 next.js 和 firebase 开发一个聊天应用程序

问题描述

我的firebase结构是:-2集合:聊天和用户-聊天集合具有:聊天中的用户(数组)(一对一),它还有其他名为“消息”的集合在SSR中,我正在尝试获取选择聊天后的聊天和消息。功能是:

export async function getServiceSideProps(context) {
const ref = db.collection("chats").doc(context.query.id);

// PREPARE MESSAGES
const messagesRes = await ref
    .collection("messages")
    .orderBy("timestamp","asc")
    .get();
const messages = messagesRes.docs.map((doc) => ({
    id:doc.id,
    ...doc.data(),
}))
.map((messages) => ({
    ...messages,
    timestamp:messages.timestamp.toDate().getTime(),
}));

//PREPARE THE CHAT
const chatRes = await ref.get();
const chat = {
    id:chatRes.id,
    ...chatRes.data(),
};
return {
    props:{
        messages:JSON.stringify(messages),
        chat:chat,
    },
};

聊天组件是:

function Chat({chat,messages}) {
console.log(chat);
const [user] = useAuthState(auth);
const recipientUserEmail = chat.users.filter((userFilter) => userFilter !== user.email)[0];
return <div className="container">
    <Head>
        <title>Chat with: {recipientUserEmail}</title>
    </Head>
    <div className="chat">
        <div className="chat__header">
            <div className="chat__header__left">
                <Avatar className="avatar" />
                <div className="header__chatInfo">
                    <h2>test@gmail.com</h2>
                    <p>Last active: 2minutes ago</p>
                </div>
            </div>
            <div className="chat__header__right">
                <IconButton>
                    <AttachFileIcon />
                </IconButton>

                <IconButton>
                    <MoreVertIcon />
                </IconButton>
            </div>
        </div>
    </div>
    <SideBar />
</div>
}

在接收者用户电子邮件的函数中,当我尝试进入用户数组时,它显示 TypeError:无法读取未定义的属性“用户”。有什么帮助吗?

标签: javascriptreactjsfirebasenext.jsserver-side-rendering

解决方案


推荐阅读