75 lines
1.9 KiB
TypeScript
75 lines
1.9 KiB
TypeScript
import { useConvex } from "convex/react"
|
|
import { useEffect, useMemo, useSyncExternalStore } from "react"
|
|
|
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
|
import type { BrowseSong } from "@otunes/convex/types"
|
|
import {
|
|
getCachedSong,
|
|
getSongSnapshot,
|
|
getSongsVersion,
|
|
requestSongs,
|
|
songFromSnapshot,
|
|
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
|
|
}
|
|
|
|
/**
|
|
* Like `useSongs` for one song, but only re-renders when that song changes
|
|
* once it is cached.
|
|
*/
|
|
export function useSong(songId: Id<"songs"> | null): BrowseSong | null {
|
|
const convex = useConvex()
|
|
const snapshot = useSyncExternalStore(
|
|
subscribeSongs,
|
|
() => getSongSnapshot(songId),
|
|
() => null
|
|
)
|
|
const song = songFromSnapshot(snapshot)
|
|
|
|
useEffect(() => {
|
|
if (songId && !song && isPersistentCacheLoaded()) {
|
|
requestSongs(convex, [songId])
|
|
}
|
|
}, [convex, songId, song, snapshot])
|
|
|
|
return song
|
|
}
|