-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathuse-prices.ts
More file actions
55 lines (43 loc) · 1.22 KB
/
Copy pathuse-prices.ts
File metadata and controls
55 lines (43 loc) · 1.22 KB
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
51
52
53
54
"use client"
import { useEffect, useState } from "react"
import type { Prices } from "@/lib/prices/coingecko"
type PriceState = {
prices: Prices | null
isLoading: boolean
error: string | null
}
export function usePrices(refreshMs = 60_000): PriceState {
const [state, setState] = useState<PriceState>({
prices: null,
isLoading: true,
error: null,
})
useEffect(() => {
let cancelled = false
async function loadPrices() {
try {
const response = await fetch("/api/prices", { cache: "no-store" })
const data = await response.json()
if (cancelled) return
if (!response.ok || !data.ok) {
throw new Error(data.error || "Price feed unavailable")
}
setState({ prices: data.prices, isLoading: false, error: null })
} catch (error) {
if (cancelled) return
setState((prev) => ({
...prev,
isLoading: false,
error: error instanceof Error ? error.message : "Price feed unavailable",
}))
}
}
loadPrices()
const interval = window.setInterval(loadPrices, refreshMs)
return () => {
cancelled = true
window.clearInterval(interval)
}
}, [refreshMs])
return state
}