From 08de2afa0ea2bc133da1f823a4822042c54fde92 Mon Sep 17 00:00:00 2001 From: Geert Rademakes Date: Wed, 6 Aug 2025 10:39:51 +0200 Subject: [PATCH] fix: Prevent infinite scroll from loading previous playlist songs - Add refs to store current playlist and search query values - Fix stale closure issue in loadPage function - Ensure infinite scroll uses current playlist, not cached values - Fixes race condition when switching playlists and scrolling --- packages/frontend/src/hooks/usePaginatedSongs.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/frontend/src/hooks/usePaginatedSongs.ts b/packages/frontend/src/hooks/usePaginatedSongs.ts index 537564e..620206e 100644 --- a/packages/frontend/src/hooks/usePaginatedSongs.ts +++ b/packages/frontend/src/hooks/usePaginatedSongs.ts @@ -23,6 +23,7 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => { const loadingRef = useRef(false); const currentPlaylistRef = useRef(playlistName); + const currentSearchQueryRef = useRef(searchQuery); const abortControllerRef = useRef(null); // Cleanup function to prevent memory leaks @@ -38,8 +39,8 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => { const loadPage = useCallback(async (page: number, search?: string, targetPlaylist?: string) => { if (loadingRef.current) return; - const searchToUse = search ?? searchQuery; - const playlistToUse = targetPlaylist ?? playlistName; + const searchToUse = search ?? currentSearchQueryRef.current; + const playlistToUse = targetPlaylist ?? currentPlaylistRef.current; // Cleanup previous request cleanup(); @@ -133,6 +134,15 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => { }; }, []); + // Update refs when values change + useEffect(() => { + currentPlaylistRef.current = playlistName; + }, [playlistName]); + + useEffect(() => { + currentSearchQueryRef.current = searchQuery; + }, [searchQuery]); + // Handle playlist changes useEffect(() => { if (currentPlaylistRef.current !== playlistName) {