Unverified Commit 1eefd006 authored by Luis Alvarez D's avatar Luis Alvarez D Committed by GitHub

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

* Updated example

* Removed isomorphic-unfetch
parent 30870b44
...@@ -7,12 +7,12 @@ ...@@ -7,12 +7,12 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"apollo-server-micro": "2.6.7", "apollo-server-micro": "2.11.0",
"graphql": "14.4.2", "graphql": "14.6.0",
"isomorphic-unfetch": "3.0.0",
"next": "latest", "next": "latest",
"react": "^16.8.6", "react": "16.13.1",
"react-dom": "^16.8.6" "react-dom": "16.13.1",
"swr": "0.1.18"
}, },
"license": "ISC" "license": "ISC"
} }
import fetch from 'isomorphic-unfetch' import useSWR from 'swr'
const Index = ({ users }) => ( const fetcher = query =>
<div> fetch('/api/graphql', {
{users.map((user, i) => (
<div key={i}>{user.name}</div>
))}
</div>
)
Index.getInitialProps = async () => {
const response = await fetch('http://localhost:3000/api/graphql', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-type': 'application/json', 'Content-type': 'application/json',
}, },
body: JSON.stringify({ query: '{ users { name } }' }), body: JSON.stringify({ query }),
}) })
.then(res => res.json())
.then(json => json.data)
const { export default function Index() {
data: { users }, const { data, error } = useSWR('{ users { name } }', fetcher)
} = await response.json()
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>
)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment