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

[example] Add SWR to api-routes-graphql #11383

Merged
merged 2 commits into from
Apr 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions examples/api-routes-graphql/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
"start": "next start"
},
"dependencies": {
"apollo-server-micro": "2.6.7",
"graphql": "14.4.2",
"isomorphic-unfetch": "3.0.0",
"apollo-server-micro": "2.11.0",
"graphql": "14.6.0",
"next": "latest",
"react": "^16.8.6",
"react-dom": "^16.8.6"
"react": "16.13.1",
"react-dom": "16.13.1",
"swr": "0.1.18"
},
"license": "ISC"
}
38 changes: 20 additions & 18 deletions examples/api-routes-graphql/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
import fetch from 'isomorphic-unfetch'
import useSWR from 'swr'

const Index = ({ users }) => (
<div>
{users.map((user, i) => (
<div key={i}>{user.name}</div>
))}
</div>
)

Index.getInitialProps = async () => {
const response = await fetch('http://localhost:3000/api/graphql', {
const fetcher = query =>
fetch('/api/graphql', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({ query: '{ users { name } }' }),
body: JSON.stringify({ query }),
})
.then(res => res.json())
lfades marked this conversation as resolved.
Show resolved Hide resolved
.then(json => json.data)

const {
data: { users },
} = await response.json()
export default function Index() {
const { data, error } = useSWR('{ users { name } }', fetcher)

return { users }
}
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>

export default Index
const { users } = data

return (
<div>
{users.map((user, i) => (
<div key={i}>{user.name}</div>
))}
</div>
)
}