简体   繁体   中英

Using getStaticProps in Nextjs

I'm making my first Nextjs project, and it is a simple blog using the JSON placeholder API. For some reason I keep getting the error that my prop posts is undefined, can someone help me??

I try to console.log() my posts, but i kepp getting undefined as result

code

import React from 'react'
import { GetStaticProps } from 'next'

import headerStyles from '../styles/header.module.css'

interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface IProps {
  posts: Post[];
}


export const getStaticProps: GetStaticProps = async () => {

  const res = await fetch('https://jsonplaceholder.typicode.com/posts')
  const posts = await res.json()

  return {
    props: {
      posts,
    }
  }
}

const Header: React.FC = () => {
  return (
    <div className={headerStyles.container}>
      <h1 className={headerStyles.heading}>My Blog</h1>
    </div>
  )
}


const Home: React.FC<IProps> = ({ posts }) => {

  console.log(posts)

  return (
    <>
    <Header />
     {posts.map(post => (
        <div key={post.id}>
          <h1> {post.title} </h1>
          <button>Go to post</button>
        </div>
      ))}
    </>
  )
}

export default Home

In your situation it will work only after build, so if you need check something without it, you have to use getInitialProps

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