url generated on server
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 const getStaticProps = async (context) =>{
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${context.params.id}`)
const article = await res.json()
return{
props:{article}
}
}
//urls are generated from server
export const getStaticPaths = async () =>{
const res = await fetch(`https://jsonplaceholder.typicode.com/posts`)
const articles = await res.json()
const ids = articles.map(article => article.id)
const paths = ids.map(id => ({params: {id: id.toString()}}))
return{
paths,
fallback: false
}
}
export default article
------------------------
//package.json
{
"name": "nextjs",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"export": "next build && next export"
},
"dependencies": {
"next": "10.0.7",
"react": "17.0.1",
"react-dom": "17.0.1"
}
}
//cmd - export static website, out folder is created
npm run export
npm install -g serve
static website served on port 8000
reference:
No comments:
Post a Comment