Unverified Commit 9e2ae699 authored by Jazib Jafri's avatar Jazib Jafri Committed by GitHub

Update api-rest-example to SSG (#11362)

* Update api-rest-example to SSG

* Use SWR for data fetching

* Updated pages
Co-authored-by: 's avatarLuis Alvarez <luis@zeit.co>
parent 48650a7d
...@@ -7,10 +7,10 @@ ...@@ -7,10 +7,10 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"isomorphic-unfetch": "3.0.0",
"next": "latest", "next": "latest",
"react": "^16.8.6", "react": "^16.8.6",
"react-dom": "^16.8.6" "react-dom": "^16.8.6",
"swr": "^0.1.18"
}, },
"license": "ISC" "license": "ISC"
} }
// Fake users data // Fake users data
const users = [ const users = [{ id: 1 }, { id: 2 }, { id: 3 }]
{
id: 1,
},
{ id: 2 },
{ id: 3 },
]
export default (req, res) => { export default (req, res) => {
// Get data from your database // Get data from your database
......
import fetch from 'isomorphic-unfetch' import useSwr from 'swr'
import Link from 'next/link' import Link from 'next/link'
const Index = ({ users }) => ( const fetcher = url => fetch(url).then(res => res.json())
<ul>
{users.map(user => (
<li key={user.id}>
<Link href="/user/[id]" as={`/user/${user.id}`}>
<a>{`User ${user.id}`}</a>
</Link>
</li>
))}
</ul>
)
Index.getInitialProps = async () => { export default function Index() {
const response = await fetch('http://localhost:3000/api/users') const { data, error } = useSwr('/api/users', fetcher)
const users = await response.json()
return { users } if (error) return <div>Failed to load users</div>
} if (!data) return <div>Loading...</div>
export default Index return (
<ul>
{data.map(user => (
<li key={user.id}>
<Link href="/user/[id]" as={`/user/${user.id}`}>
<a>{`User ${user.id}`}</a>
</Link>
</li>
))}
</ul>
)
}
import fetch from 'isomorphic-unfetch' import { useRouter } from 'next/router'
import useSwr from 'swr'
const User = ({ user }) => <div>{user.name}</div> const fetcher = url => fetch(url).then(res => res.json())
User.getInitialProps = async ({ query: { id } }, res) => { export default function User() {
const response = await fetch(`http://localhost:3000/api/user/${id}`) const router = useRouter()
const user = await response.json() const { data, error } = useSwr(`/api/user/${router.query.id}`, fetcher)
return { user } if (error) return <div>Failed to load user</div>
} if (!data) return <div>Loading...</div>
export default User return <div>{data.name}</div>
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment