forked from
chadtmiller.com/slices-teal-relay
Teal.fm frontend powered by slices.network
tealfm-slices.wisp.place
tealfm
slices
1import { useState, useEffect } from "react";
2import { albumArtCache } from "./albumArtCache";
3
4export function useAlbumArt(releaseMbId: string | null | undefined) {
5 const [albumArtUrl, setAlbumArtUrl] = useState<string | null>(null);
6 const [isLoading, setIsLoading] = useState(false);
7
8 useEffect(() => {
9 if (!releaseMbId) return;
10
11 // Check cache first
12 if (albumArtCache.has(releaseMbId)) {
13 setAlbumArtUrl(albumArtCache.get(releaseMbId) || null);
14 setIsLoading(false);
15 return;
16 }
17
18 setIsLoading(true);
19
20 const fetchAlbumArt = async () => {
21 try {
22 // Fetch cover art from Cover Art Archive
23 const coverArtUrl = `https://coverartarchive.org/release/${releaseMbId}/front-250`;
24
25 // Check if cover art exists
26 const coverArtResponse = await fetch(coverArtUrl, { method: "HEAD" });
27
28 if (coverArtResponse.ok) {
29 setAlbumArtUrl(coverArtUrl);
30 albumArtCache.set(releaseMbId, coverArtUrl);
31 } else {
32 setAlbumArtUrl(null);
33 albumArtCache.set(releaseMbId, null);
34 }
35 } catch (error) {
36 console.error("Error fetching album art:", error);
37 setAlbumArtUrl(null);
38 albumArtCache.set(releaseMbId, null);
39 } finally {
40 setIsLoading(false);
41 }
42 };
43
44 fetchAlbumArt();
45 }, [releaseMbId]);
46
47 return { albumArtUrl, isLoading };
48}