Skip to content

Instantly share code, notes, and snippets.

@khoa-le
Created April 7, 2020 03:52
Show Gist options
  • Save khoa-le/0c405badb3ca33d40566026e1c921e76 to your computer and use it in GitHub Desktop.
Save khoa-le/0c405badb3ca33d40566026e1c921e76 to your computer and use it in GitHub Desktop.
next.js snippet
##Use SWR to call ajax in client site
import useSWR from 'swr'
const fetcher = url => fetch(url, {
'Content-Type': 'application/json',
}).then(r => r.json());
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
### Use fetch api from server
import fetch from 'isomorphic-unfetch'
export const getServerSideProps = async (context) => {
const res = await fetch(`http://localhost:3000/api/products/${context.params.id}`)
const products = await res.json()
return {props: {...products}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment