gpt4 book ai didi

javascript - Next.js 读取 Firestore 数据

转载 作者:行者123 更新时间:2023-12-05 05:46:31 27 4
gpt4 key购买 nike

我发现这个 Next.js starter 可以在 Firestore v9 中读取数据,但是它在 onclick 之后显示数据。在 Next.js 中,我如何将其编写为无需点击即可实际使用的数据?

import { db } from '@/lib/firebase/initFirebase'
import { doc, getDoc } from "firebase/firestore"
import { useUser } from '@/lib/firebase/useUser'
import Button from 'react-bootstrap/Button'

const ReadDataFromCloudFirestore = () => {
const { user } = useUser()
const readData = async () => {
try {
const userDoc = doc(db, "myCollection", user.id)
await getDoc(userDoc).then((doc) => {
if (doc.exists()) {
console.log(doc.data())
}
})
alert('Data was successfully fetched from cloud firestore! Close this alert and check console for output.')
} catch (error) {
console.log(error)
alert(error)
}
}

return (
<div style={{ margin: '5px 0' }}>
<Button onClick={readData} style={{ width: '100%' }}>Read Data From Cloud Firestore</Button>
</div>
)
}

export default ReadDataFromCloudFirestore

最佳答案

这可以通过简单地删除函数并在页面打开时运行 try/catch 来实现。

const ReadDataFromCloudFirestore = () => {


const { user } = useUser()
try {
const userDoc = doc(db, "myCollection", user.id)
await getDoc(userDoc).then((doc) => {
if (doc.exists()) {
console.log(doc.data())
}
})
alert('Data was successfully fetched from cloud firestore! Close this alert and check console for output.')
} catch (error) {
console.log(error)
alert(error)
}
}

关于javascript - Next.js 读取 Firestore 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71166843/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com