Skip to content

Commit

Permalink
Update data-fetch example to SSG (vercel#11017)
Browse files Browse the repository at this point in the history
* Update to SSG

* Change to getServerSideProps

* Fix lint

* Update
  • Loading branch information
asotoglez authored and ScriptedAlchemy committed Mar 17, 2020
1 parent 923ac97 commit 042c143
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 12 deletions.
2 changes: 1 addition & 1 deletion examples/data-fetch/README.md
Expand Up @@ -3,7 +3,7 @@
Next.js was conceived to make it easy to create universal apps. That's why fetching data
on the server and the client when necessary is so easy with Next.

Using `getInitialProps` fetches data on the server for SSR and then on the client when the component is re-mounted (not on the first paint).
Using `getStaticProps` fetches data at built time from a page, Next.js will pre-render this page at build time.

## Deploy your own

Expand Down
2 changes: 1 addition & 1 deletion examples/data-fetch/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.4",
"react-dom": "^16.8.4"
},
Expand Down
14 changes: 9 additions & 5 deletions examples/data-fetch/pages/index.js
@@ -1,22 +1,26 @@
import React from 'react'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'
import fetch from 'node-fetch'

function Index(props) {
function Index({ stars }) {
return (
<div>
<p>Next.js has {props.stars} ⭐️</p>
<p>Next.js has {stars} ⭐️</p>
<Link href="/preact">
<a>How about preact?</a>
</Link>
</div>
)
}

Index.getInitialProps = async () => {
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/zeit/next.js')
const json = await res.json() // better use it inside try .. catch
return { stars: json.stargazers_count }
return {
props: {
stars: json.stargazers_count,
},
}
}

export default Index
14 changes: 9 additions & 5 deletions examples/data-fetch/pages/preact.js
@@ -1,22 +1,26 @@
import React from 'react'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'
import fetch from 'node-fetch'

function Preact(props) {
function Preact({ stars }) {
return (
<div>
<p>Preact has {props.stars}</p>
<p>Preact has {stars}</p>
<Link href="/">
<a>I bet Next.js has more stars (?)</a>
</Link>
</div>
)
}

Preact.getInitialProps = async () => {
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/developit/preact')
const json = await res.json() // better use it inside try .. catch
return { stars: json.stargazers_count }
return {
props: {
stars: json.stargazers_count,
},
}
}

export default Preact

0 comments on commit 042c143

Please sign in to comment.