Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js read Firestore data

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
like image 528
Steve Avatar asked Sep 10 '26 13:09

Steve


1 Answers

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)
            }
        }
like image 60
EJZ Avatar answered Sep 12 '26 03:09

EJZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!