未验证 提交 9ff7339e 编写于 作者: T Tim Neutkens 提交者: GitHub

Add @zeit/fetch example (#9029)

上级 de670b38
# @zeit/fetch example
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/segmentio/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npx create-next-app --example with-zeit-fetch-app
# or
yarn create next-app --example with-zeit-fetch-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-zeit-fetch
cd with-zeit-fetch
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
This example shows how to use [`@zeit/fetch`](https://npmjs.com/zeit/fetch) in a Next.js application.
import fetch from 'isomorphic-fetch'
export default fetch
{
"browser": "./browser.js",
"main": "./server.js"
}
\ No newline at end of file
import zeitFetch from '@zeit/fetch'
export default zeitFetch()
{
"name": "data-fetch",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@zeit/fetch": "5.1.1",
"next": "latest",
"node-fetch": "2.6.0",
"react": "^16.8.4",
"react-dom": "^16.8.4",
"unfetch": "4.1.0"
},
"license": "ISC"
}
import React from 'react'
import Link from 'next/link'
import fetch from '../fetch'
function Index (props) {
return (
<div>
<p>Next.js has {props.stars} ⭐️</p>
<Link href='/preact'>
<a>How about preact?</a>
</Link>
</div>
)
}
Index.getInitialProps = async () => {
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 }
}
export default Index
import React from 'react'
import Link from 'next/link'
import fetch from '../fetch'
function Preact (props) {
return (
<div>
<p>Preact has {props.stars} </p>
<Link href='/'>
<a>I bet Next.js has more stars (?)</a>
</Link>
</div>
)
}
Preact.getInitialProps = async () => {
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 }
}
export default Preact
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册