I found this Next.js starter to read data in Firestore v9, but it shows data after onclick. In Next.js how would I write this to actually be consumable data without the click?
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
This can be accomplished by simply removing the function and running the try/catch when the page opens.
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)
}
}