-
-
Notifications
You must be signed in to change notification settings - Fork 110
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add fetchJSON utility, based on best-practices from Vercel (SWR offic…
…ial recommendations) for server-side fetching
- Loading branch information
1 parent
fd494c6
commit f13ee73
Showing
1 changed file
with
25 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
/** | ||
* Uses built-in Next.js "fetch" lib and attempt to transform response as JSON | ||
* | ||
* Meant to be used from the server side. | ||
* Fetching from the client side should rather use SWR hook. | ||
* | ||
* @example Server-side use "fetchJSON" | ||
* @see https://github.com/vercel/swr/blob/master/examples/server-render/pages/%5Bpokemon%5D.js#L40 | ||
* | ||
* @example Client-side use "useSWR" with "initialData" pre-fetched from getServerSideProps | ||
* @see https://github.com/vercel/swr/blob/master/examples/server-render/pages/%5Bpokemon%5D.js#L9 | ||
* | ||
* @param args | ||
* @see https://nextjs.org/blog/next-9-4#improved-built-in-fetch-support | ||
*/ | ||
const fetchJSON: <JSON = any>( | ||
input: RequestInfo, | ||
init?: RequestInit, | ||
) => Promise<JSON> = async (...args) => { | ||
const res = await fetch(...args); | ||
if (!res.ok) throw new Error(res.statusText); | ||
return res.json(); | ||
}; | ||
|
||
export default fetchJSON; |