Home > Software design >  Failing to read data from firestore using nextjs
Failing to read data from firestore using nextjs

Time:12-25

I am trying to read data from firestore using getStaticprops on nextjs but instead, I am getting back an empty page. I have followed the docs on how to extract data using getStaticprops but for some reason, it is not working. This is how my code looks like

import React from 'react'
import { db } from '../firebase'
import { collection, getDocs } from "firebase/firestore";

const reference = collection(db, "students");

export const getStaticProps = async () => {
    const data = await getDocs(reference);
    const students = data.docs.map(doc => ({...doc.data(), id: doc.id}));

    return {
        props: {
           students
        }
    }
}

function Card({students = []}) {
    return (
        <div>
        <p>This is just a test</p>
        {students.map(student => (
            <h1>{student.surname}</h1>
        ))}
    </div>
  )
}

export default Card

Where could I be going wrong?

CodePudding user response:

After some analysis and tried sample code here are my understandings.

getStaticProps is used only for static site generation. ie. if your page always renders same data (which you are getting from api) then you can use getStaticProps.

For example, in your case you defined Card component with static props. This component will be having a route say /Card.

When you run next build the data will be obtained from server and used for that page. then npm start. when you access /Card route, this data will be available.(note: getStaticProps will only be called in build time)

But if you call the same component from other pages, then the static props will not be considered you have to provide your own props like

<Card students={[]} />

if you want to get student data whenever the page is rendered, then make the api call inside useEffect().

Note: getStaticProps will only be called in build time thats why you were not getting any console.log() in console.It will be logged while building the site.

CodePudding user response:

In firebase documentation examples, (https://firebase.google.com/docs/firestore/query-data/get-data#web-version-9_6)

the response is used as array (data.forEach).But in your code you're accessing it like object (data.docs).

Can you try this,

const students = data.map(doc => ({...doc.data(), id: doc.id}));
  • Related