Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example on how to use fetch + mutate to prefetch data #120

Merged
merged 2 commits into from
Nov 15, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions examples/prefetch/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Prefetch

## One-Click Deploy

Deploy your own SWR project with ZEIT Now.

[![Deploy with ZEIT Now](https://zeit.co/button)](https://zeit.co/new/project?template=https://github.com/zeit/swr/tree/master/examples/prefetch)

## How to Use

Download the example:

```bash
curl https://codeload.github.com/zeit/swr/tar.gz/master | tar -xz --strip=2 swr-master/examples/prefetch
cd prefetch
```

Install it and run:

```bash
yarn
yarn dev
# or
npm install
npm run dev
```

Deploy it to the cloud with [now](https://zeit.co/home) ([download](https://zeit.co/download))

```
now
```

## The Idea behind the Example

This examples show how you could combine fetch and mutate to prefetch data to be used by SWR later.

In the example the list of projects page will prefetch every project data, and the project details will prefetch the list of projects in case you accessed directly the details without seeing the list before.
6 changes: 6 additions & 0 deletions examples/prefetch/libs/fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import fetch from 'isomorphic-unfetch'

export default async function (...args) {
const res = await fetch(...args)
return await res.json()
}
18 changes: 18 additions & 0 deletions examples/prefetch/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "prefetch",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"isomorphic-unfetch": "3.0.0",
"next": "9.1.1",
"react": "16.11.0",
"react-dom": "16.11.0",
"swr": "latest"
},
"scripts": {
"dev": "next",
"start": "next start",
"build": "next build"
}
}
29 changes: 29 additions & 0 deletions examples/prefetch/pages/[user]/[repo].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import React from 'react'
import Link from 'next/link'
import fetch from '../../libs/fetch'

import useSWR, { mutate } from 'swr'

export default () => {
const id = typeof window !== 'undefined' ? window.location.pathname.slice(1) : ''
const { data } = useSWR('/api/data?id=' + id, fetch)

React.useEffect(() => {
fetch('/api/data')
.then(projects => mutate('/api/data', projects, false))
}, []);

return <div style={{ textAlign: 'center' }}>
<h1>{id}</h1>
{
data ? <div>
<p>forks: {data.forks_count}</p>
<p>stars: {data.stargazers_count}</p>
<p>watchers: {data.watchers}</p>
</div> : 'loading...'
}
<br />
<br />
<Link href="/"><a>Back</a></Link>
</div>
}
23 changes: 23 additions & 0 deletions examples/prefetch/pages/api/data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import fetch from 'isomorphic-unfetch'

const projects = [
'facebook/flipper', 'vuejs/vuepress', 'rust-lang/rust', 'zeit/next.js'
]

export default (req, res) => {
if (req.query.id) {
// a slow endpoint for getting repo data
fetch(`https://api.github.com/repos/${req.query.id}`)
.then(resp => resp.json())
.then(data => {
setTimeout(() => {
res.json(data)
}, 2000)
})

return
}
setTimeout(() => {
res.json(projects)
}, 2000)
}
31 changes: 31 additions & 0 deletions examples/prefetch/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import React from 'react'
import Link from 'next/link'
import fetch from '../libs/fetch'

import useSWR, { mutate } from 'swr'

export default () => {
const { data } = useSWR('/api/data', fetch)

React.useEffect(() => {
if (!data) return
if (data.length === 0) return
data.forEach(project => {
fetch(`https://api.github.com/repos/${project}`)
.then(projectData => {
mutate(`/api/data?id=${project}`, projectData, false)
})
})
}, [data]);

return <div style={{ textAlign: 'center' }}>
<h1>Trending Projects</h1>
sergiodxa marked this conversation as resolved.
Show resolved Hide resolved
<div>
{
data ? data.map(project =>
<p key={project}><Link href='/[user]/[repo]' as={`/${project}`}><a>{project}</a></Link></p>
) : 'loading...'
}
</div>
</div>
}