Thursday, 18 February 2021

nextjs 2 getStaticProps, getServerSideProp


click on tab to see article details


//pages/index.js

import Head from 'next/head'
import ArticleList from '../components/ArticleList'

export default function Home({articles}) {
  //console.log(articles)
  return (
    <div>
      <Head>
        <title>WebDev Newz</title>
        <meta name='keywors' content='web development'/>
      </Head>

      <ArticleList articles={articles} />
    </div>
  )
}

export const getStaticProps = async () => {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts?_limit=6`)
  const articles = await res.json()

  return{
    props:{articles}
  }
}

---------------------------------
//pages/article/[id]/index.js

import {useRouter} from 'next/router'
import Link from 'next/link'

const article = ({article}) => {
    //const router = useRouter()
    //const {id} = router.query

    //return <div>This is article {id}</div>
    return (
    <div>
        <h1>{article.title}</h1>
        <p>{article.body}</p>
        <br/>
        <Link href='/'>Go Back</Link>
    </div>)
}

export const getServerSideProps = async (context) =>{
    const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${context.params.id}`)
    
    const article = await res.json()
    
    return{
        props:{article}
      }
}

export default article

--------------------------------
//components/ArticleItem.js

import Link from 'next/link'
import articleStyles from '../styles/Article.module.css'

const ArticleItem = ({article}) => {
    return (
        <Link href="/article/[id]" as={`/article/${article.id}`}>
            <a className={articleStyles.card}>
                <h3>{article.title} &rarr;</h3>
            </a>
        </Link>
    )
}

export default ArticleItem

------------------------
reference:

getStaticProps vs getServerSideProps

server side fetch increases performance as the server will generally have a faster connection to the data source. It also increases security by exposing less of the data fetching logic.

No comments:

Post a Comment