Created
April 7, 2020 03:52
-
-
Save khoa-le/0c405badb3ca33d40566026e1c921e76 to your computer and use it in GitHub Desktop.
next.js snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##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