Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

next js getStaticPaths

// create a post folder and index.js file in pages/posts folder
import Link from 'next/link';
const Posts = ({ posts }) => (
  <div>
    {
      posts.map(post => (
        <div>
          <Link href={`/posts/${post.id}`}><a style={{fontSize:'20px',textDecoration: 'underline'}}>{post.title}</a></Link>
          <p>{post.body}</p>
        </div>
      ))
    }
  </div>
)

export async function getServerSideProps() {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts`)
  const posts = await res.json()
  return { props: { posts } }
}
export default Posts;



// then add another file in 
pagesposts[id].js

function Post({ post }) {
    // Render post...
    return (
        <div>
            <h1>{post.title}</h1>
            <p>{post.body}</p>
        </div>
    )
}

export async function getStaticPaths() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts')
    const posts = await res.json()
    const paths = posts.map((post) => ({
        params: { id: post.id.toString() },
    }))

    // We'll pre-render only these paths at build time.
    // { fallback: false } means other routes should 404.
    return { paths, fallback: true }
}

export async function getStaticProps({ params }) {
    const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`)
    const post = await res.json()
    return { 
        props: { post },
        revalidate: 10,
    }
}
export default Post
 
PREVIOUS NEXT
Tagged: #js #getStaticPaths
ADD COMMENT
Topic
Name
2+7 =