From 7d78bf4d2111af87636069ee2d35d6323ffc96be Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Sat, 5 Feb 2022 15:18:48 +0200 Subject: Get stuff running --- src/api.ts | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/api.ts (limited to 'src/api.ts') diff --git a/src/api.ts b/src/api.ts new file mode 100644 index 0000000..7fd9e64 --- /dev/null +++ b/src/api.ts @@ -0,0 +1,50 @@ +import useSWR, { SWRResponse } from "swr" + +const API_URL = import.meta.env.VITE_API_URL + +const fetcher = (path: string) => fetch(`${API_URL}${path}`) + .then(res => res.json()) + .catch((err) => { + console.error(`An error occurred when fetching API path ${path}`) + console.error(err) + throw err + }) + +interface Snippet { + id: string + title: string + content: string +} + +interface APISuccess { + readonly type: "success" + data: D +} + +interface APILoading { + readonly type: "loading" +} + +interface APIFailed { + readonly type: "failed" + error: E +} + +type APIResult = APISuccess | APILoading | APIFailed + +const mapSWRResult = ({ data, error }: SWRResponse): APIResult => { + if (error !== undefined) { + return { type: "failed", error } + } + + const isLoading = data === undefined + if (isLoading) { + return { type: "loading" } + } + + return { type: "success", data } +} + +export const useSnippets = () => mapSWRResult( + useSWR("/snippets", fetcher), +) -- cgit v1.3