blob: 7fd9e64cb2d5041cd1ae036f746c2687c7227b32 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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<D> {
readonly type: "success"
data: D
}
interface APILoading {
readonly type: "loading"
}
interface APIFailed<E> {
readonly type: "failed"
error: E
}
type APIResult<D, E> = APISuccess<D> | APILoading | APIFailed<E>
const mapSWRResult = <D, E>({ data, error }: SWRResponse<D, E>): APIResult<D, E> => {
if (error !== undefined) {
return { type: "failed", error }
}
const isLoading = data === undefined
if (isLoading) {
return { type: "loading" }
}
return { type: "success", data }
}
export const useSnippets = () => mapSWRResult<Snippet[], Error>(
useSWR("/snippets", fetcher),
)
|