Files
otunes/apps/web/lib/song-cache.ts
joshuafhiggins Verified 4a740c918c feat(mobile): add client-first playback caching
- Cache queries and songs across mobile and web
- Show cached content and skeletons during loading
- Move shared playback and cache utilities into Convex client
2026-10-08 17:07:49 -04:00

55 lines
1.4 KiB
TypeScript

import { useConvex } from "convex/react"
import { useEffect, useMemo, useSyncExternalStore } from "react"
import type { Id } from "@otunes/convex/_generated/dataModel"
import {
getCachedSong,
getSongsVersion,
requestSongs,
subscribeSongs,
} from "@otunes/convex/client/song-cache"
import { isPersistentCacheLoaded } from "@/lib/persistent-cache"
export {
albumDetailSongs,
getCachedSong,
rememberSongs,
} from "@otunes/convex/client/song-cache"
/**
* Resolves song metadata from the persistent song cache, fetching anything
* missing in batches. Entries are `undefined` until loaded.
*/
export function useSongs(songIds: readonly Id<"songs">[]) {
const convex = useConvex()
const songsVersion = useSyncExternalStore(
subscribeSongs,
getSongsVersion,
() => 0
)
const songs = useMemo(
() => songIds.map((songId) => getCachedSong(songId)),
// songsVersion invalidates the lookup when the cache changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
[songIds, songsVersion]
)
useEffect(() => {
if (!isPersistentCacheLoaded()) {
return
}
const missing = songIds.filter((songId, index) => !songs[index])
if (missing.length > 0) {
requestSongs(convex, missing)
}
}, [convex, songIds, songs])
return songs
}
export function useSong(songId: Id<"songs"> | null) {
const songIds = useMemo(() => (songId ? [songId] : []), [songId])
return useSongs(songIds)[0] ?? null
}