|
| 1 | +import { useEffect, useState } from 'react' |
| 2 | +import type { Playlist } from '../types' |
| 3 | + |
| 4 | +const LOCAL_STORAGE_KEY = 'cached_playlists' |
| 5 | + |
| 6 | +// Mock function for caching, can be replaced with real implementation or for testing |
| 7 | +// eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 8 | +export function mockCachePlaylists(playlists: Playlist[]) { |
| 9 | + // For now, just log to console |
| 10 | + console.log('Mock caching playlists') |
| 11 | + return true |
| 12 | +} |
| 13 | + |
| 14 | +function arePlaylistsEqual(a: Playlist[], b: Playlist[]): boolean { |
| 15 | + return JSON.stringify(a) === JSON.stringify(b) |
| 16 | +} |
| 17 | + |
| 18 | +export function useCachedData(playlists: Playlist[] | null) { |
| 19 | + const [cachedPlaylists, setCachedPlaylists] = useState<Playlist[]>(() => { |
| 20 | + const cachedRaw = localStorage.getItem(LOCAL_STORAGE_KEY) |
| 21 | + |
| 22 | + return cachedRaw ? JSON.parse(cachedRaw) : [] |
| 23 | + }) |
| 24 | + |
| 25 | + const [loadingPlaylist, setLoadingPlaylist] = useState<boolean>(false) |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + const updateData = async () => { |
| 29 | + if(!playlists || !Array.isArray(playlists)) { |
| 30 | + console.warn('Invalid playlists data, skipping caching.') |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + if (!arePlaylistsEqual(playlists, cachedPlaylists)) { |
| 35 | + setLoadingPlaylist(true) |
| 36 | + |
| 37 | + console.log('Playlists changed, updating cached data...') |
| 38 | + |
| 39 | + const result = mockCachePlaylists(playlists) |
| 40 | + |
| 41 | + if (result !== false) { |
| 42 | + console.warn('Caching function returned false, not updating local storage.') |
| 43 | + |
| 44 | + localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(playlists)) |
| 45 | + setCachedPlaylists(playlists) |
| 46 | + } |
| 47 | + |
| 48 | + console.log('Playlists cached:', playlists) |
| 49 | + |
| 50 | + setLoadingPlaylist(false) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + updateData() |
| 55 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 56 | + }, [playlists]) |
| 57 | + |
| 58 | + return { cachedData: cachedPlaylists, isCaching: loadingPlaylist } |
| 59 | +} |
0 commit comments