Data fetched from getStaticProps is not displayed in page component

Viewed 1168

I am very new to Next.js and I am trying out the getStaticPaths and getStaticProps with firebase for the details page.

import firebase from '../../firebase'

export const getStaticPaths = async () => {
  let posts = []
  const ref = firebase.firestore().collection('posts')
  try {
    let allPosts = await ref.get()
    for (const doc of allPosts.docs) {
      console.log(doc.id, '=>', doc.data())
      console.log('the id is....')

      let data = doc.data()
      console.log(data.ytid)
      posts.push({
        title: data.title,
        ytid: data.ytid,
      })
    }
  } catch (e) {
    console.log(e)
  }
  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => ({
    params: { id: post.ytid },
  }))

  return { paths, fallback: false }
}

export const getStaticProps = async (context) => {
  const id = context.params.id

  console.log('id is')
  console.log(id)

  let post = []

  try {
    const ref = firebase.firestore().collection('posts').where('ytid', '==', id)

    const qsnapshot = await ref.get()
    qsnapshot.forEach((doc) => {
      const data = doc.data()
      console.log('the title is...')
      console.log(data.title)
      post.title = data.title
      post.ytid = data.ytid
    })
    return {
      props: { post: post },
      revalidate: 1,
    }
  } catch (e) {
    console.log(e)
  }
}

const Details = ({ post }) => {
  console.log('posting...')
  console.log(post.title)
  return (
    <div>
      <div className='mx-auto'>
        <h2>Post Details Page</h2>
        <h3 className='text-black'>{post.title}</h3>
        <h4>Details here</h4>
      </div>
    </div>
  )
}

export default Details

Somehow the post.title is not displayed in the h3 tag in the details page but when I look at the console terminal, it is printed there. So it is shown in the backend but not in the frontend. Not very sure if it is caused by some configuration issue and any help would be greatly appreciated.

1 Answers

In your getStaticProps function, you initialized let post = [] (by mistake I assumed?), even though you can add properties to an array (which is an object), the properties are ignored when the array is converted to JSON.

When a page with getStaticProps is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running getStaticProps. doc

Change let post = [] to let post = {} and it should work just fine.

Related