From 74a9fff1b2f11fb2983f59802823e8e4e5789874 Mon Sep 17 00:00:00 2001 From: Tobias Hegge Date: Tue, 15 Sep 2026 12:50:10 +0200 Subject: [PATCH] made sure search is persistent on reload --- webdev-prosjekt1/src/App.tsx | 22 +++++++++++++++---- webdev-prosjekt1/src/api/types.ts | 6 +++++ webdev-prosjekt1/src/components/Header.tsx | 13 +++++++++-- webdev-prosjekt1/src/components/Searchbar.tsx | 11 +++++++--- 4 files changed, 43 insertions(+), 9 deletions(-) diff --git a/webdev-prosjekt1/src/App.tsx b/webdev-prosjekt1/src/App.tsx index 65bbf73..86688f8 100644 --- a/webdev-prosjekt1/src/App.tsx +++ b/webdev-prosjekt1/src/App.tsx @@ -12,7 +12,7 @@ import { TrackCard } from './components/TrackCard'; import { AlbumCard } from './components/AlbumCard'; import { ArtistCard } from './components/ArtistCard'; import { FilterPopup, EMPTY_FILTERS } from './components/FilterPopup'; -import type { Album, AlbumTrack, Artist, Track } from './api/types'; +import type { Album, AlbumTrack, Artist, SearchResult, StoredSearch, Track } from './api/types'; import { fetchTrack, search } from './api/spotify'; import filterIcon from './assets/filter.png'; import musicWizImage from './assets/musicwiz.png'; @@ -27,7 +27,8 @@ const readStoredItem = (key: string): T | null => { }; function App() { - const [query, setQuery] = useState(''); + const storedSearch = readStoredItem('music-wiz-search'); + const [query, setQuery] = useState(storedSearch?.query ?? ''); const [isFilterOpen, setIsFilterOpen] = useState(false); const [filters, setFilters] = useState(EMPTY_FILTERS); const [currentPath, setCurrentPath] = useState(window.location.pathname); @@ -97,6 +98,7 @@ function App() { setCurrentPath(path); }; const handleSearch = (nextQuery: string) => setQuery(nextQuery); + const handleHome = () => setQuery(''); // Spotify's artist "genres" field is unreliable (often empty), so ask Spotify // to do the genre filtering itself via the "genre:" search field filter. const genreFilterClause = filters.genres.length === 1 ? ` genre:"${filters.genres[0]}"` : ''; @@ -126,8 +128,20 @@ function App() { queryKey: ['search', effectiveQuery], queryFn: () => search(effectiveQuery), enabled: query.trim().length > 0, + initialData: storedSearch?.effectiveQuery === effectiveQuery ? storedSearch.results : undefined, }); + useEffect(() => { + if (!results || !query.trim()) return; + + const searchToStore: StoredSearch = { + query, + effectiveQuery, + results: results as SearchResult, + }; + localStorage.setItem('music-wiz-search', JSON.stringify(searchToStore)); + }, [effectiveQuery, query, results]); + const artistGenresById = new Map(); results?.artists.forEach((artist) => { if (artist.genres) { @@ -185,9 +199,9 @@ function App() { return (
-
+
- +