Skip to content

Commit

Permalink
feat: update api-routes example to SSG (#11019)
Browse files Browse the repository at this point in the history
* feat: update api-routes example to SSG

* Update examples/api-routes/components/Person.js

Co-authored-by: Luis Alvarez D <luis@zeit.co>
  • Loading branch information
josiahwiebe and Luis Alvarez D committed Mar 12, 2020
1 parent 0f0013b commit fe4da73
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 9 deletions.
2 changes: 1 addition & 1 deletion examples/api-routes/components/Person.js
Expand Up @@ -2,7 +2,7 @@ import Link from 'next/link'

export default ({ person }) => (
<li>
<Link href={`/person?id=${person.id}`}>
<Link href="/person/[id]" as={`/person/${person.id}`}>
<a>{person.name}</a>
</Link>
</li>
Expand Down
2 changes: 1 addition & 1 deletion examples/api-routes/package.json
Expand Up @@ -7,8 +7,8 @@
"start": "next start"
},
"dependencies": {
"isomorphic-unfetch": "3.0.0",
"next": "latest",
"node-fetch": "2.6.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
Expand Down
6 changes: 3 additions & 3 deletions examples/api-routes/pages/index.js
@@ -1,5 +1,5 @@
import Person from '../components/Person'
import fetch from 'isomorphic-unfetch'
import fetch from 'node-fetch'

const Index = ({ people }) => (
<ul>
Expand All @@ -9,11 +9,11 @@ const Index = ({ people }) => (
</ul>
)

Index.getInitialProps = async () => {
export async function getStaticProps() {
const response = await fetch('http://localhost:3000/api/people')
const people = await response.json()

return { people }
return { props: { people } }
}

export default Index
@@ -1,4 +1,4 @@
import fetch from 'isomorphic-unfetch'
import fetch from 'node-fetch'

const Person = ({ data, status }) =>
status === 200 ? (
Expand Down Expand Up @@ -30,11 +30,29 @@ const Person = ({ data, status }) =>
<p>{data.message}</p>
)

Person.getInitialProps = async ({ query }) => {
const response = await fetch(`http://localhost:3000/api/people/${query.id}`)
export async function getStaticPaths() {
const response = await fetch('http://localhost:3000/api/people')
const data = await response.json()

const paths = data.map(person => ({
params: {
id: person.id,
},
}))

return { paths, fallback: false }
}

export async function getStaticProps({ params }) {
const response = await fetch(`http://localhost:3000/api/people/${params.id}`)
const data = await response.json()
return { data, status: response.status }

return {
props: {
data,
status: response.status,
},
}
}

export default Person

0 comments on commit fe4da73

Please sign in to comment.