javascript - 从 firebase 调用集合是空的
问题描述
我正在尝试从名为“通知”的 firebase 集合中获取一些信息,以便在用户的问题得到解答时通知用户。问题是当我调用集合时,它会以空数组的形式返回。
这是我从 firebase 调用信息的代码。我使用控制台日志在第 34 行调用数据库:
import React, { useEffect, useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Popper from "@material-ui/core/Popper";
import NotificationsIcon from "@material-ui/icons/Notifications";
import "../Style/Header.css";
import db from "../firebase";
const useStyles = makeStyles((theme) => ({
paper: {
border: "1px solid",
padding: theme.spacing(1),
backgroundColor: theme.palette.background.paper,
zIndex: "10",
},
}));
export default function SimplePopper() {
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
const [notifications, setNotifications] = useState([]);
const handleClick = (event) => {
setAnchorEl(anchorEl ? null : event.currentTarget);
};
const open = Boolean(anchorEl);
const id = open ? "simple-popper" : undefined;
useEffect(() => {
db.collection("notifications")
// .where("user.askerUserId", "==", auth.currentUser.uid)
.orderBy("timestamp", "desc")
.onSnapshot((snapshot) => {
console.log(snapshot.docs);
setNotifications(
snapshot.docs.map((doc) => ({
id: doc.id,
content: doc.data().content,
}))
);
});
}, []);
return (
<div className="header__icon">
<NotificationsIcon
aria-describedby={id}
type="button"
onClick={handleClick}
/>
<Popper id={id} open={open} anchorEl={anchorEl} style={{ zIndex: 100 }}>
<div className={classes.paper}>
<ul className="notifications">
{notifications.map((notification) => (
<li key={notification.id}>{notification.content}</li>
))}
</ul>
</div>
</Popper>
</div>
);
}
解决方案
LeadDreamer 指出了这一点。问题是当我将文档发布到firestore时我没有正确标记“时间戳”字段,我认为firebase会自动添加它们。相反,我将其列为“时间”。
以下是我更改的 firebase 函数 index.js 文件中的代码,使其工作:
exports.answerCreated = functions.firestore
.document("questions/{questionsId}/answer/{answerId}")
.onCreate(async (doc) => {
const project = doc.data();
const { displayName, uid } = project.user;
const questionSnapshot = await admin
.firestore()
.collection("questions")
.doc(project.questionId)
.get();
const question = questionSnapshot.data();
if (question) {
const { user } = question;
const notification = {
content: "Added an answer",
user: {
askerUserId: user.uid,
displayName,
uid,
},
timestamp: admin.firestore.FieldValue.serverTimestamp(),
};
return createNotification(notification);
}
});
推荐阅读
- c# - 更新 .NET Standard 库以使用 ASP.NET Core 2.2 和 3.0
- doctrine - 如何为 bin/console 启用学说:schema 命名空间?
- c# - Webforms - DataBinding() GridView - 如何绑定具有列表的列表
财产? - c# - AspNet Core SignalR - 在单声道上运行时的依赖性问题
- javascript - 使用 Aura 开发的 salesforce 应用程序无法解决 IE11 兼容性问题
- javascript - 为什么从 chrome 扩展运行的 jQuery 代码与从浏览器控制台运行的 jQuery 代码的行为不同?
- c# - 不同的数据库连接可以更新 Oracle 中的同一事务吗?
- python - Django-“python manage.py runserver”不工作
- python - 运行带有exec问题nltk的python脚本
- php - SQLSTATE[HY000] [1045] 用户 'root'@'localhost' 在 ../laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70 的访问被拒绝