Skip to content

Commit

Permalink
Add fetchJSON utility, based on best-practices from Vercel (SWR offic…
Browse files Browse the repository at this point in the history
…ial recommendations) for server-side fetching
  • Loading branch information
Vadorequest committed Jun 2, 2020
1 parent fd494c6 commit f13ee73
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/utils/api/fetchJSON.ts
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;

0 comments on commit f13ee73

Please sign in to comment.