- Cache queries and songs across mobile and web - Show cached content and skeletons during loading - Move shared playback and cache utilities into Convex client
50 lines
1.4 KiB
TypeScript
50 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)
|
|
|
|
const songs = useMemo(
|
|
() => songIds.map((songId) => getCachedSong(songId)),
|
|
// songsVersion invalidates the lookup when the cache changes.
|
|
[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
|
|
}
|