简体   繁体   中英

NextJS: getStaticPaths and getStaticProps

I am very new to NextJS 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM