From 6d53511695f228c13bff7301277de296c652af53 Mon Sep 17 00:00:00 2001 From: ellawaal Date: Fri, 11 Sep 2026 09:57:54 +0200 Subject: [PATCH] Implementert lagring av filter/sortering i sessionStorage --- src/App.tsx | 5 +++-- src/hooks/useSessionStorage.ts | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 src/hooks/useSessionStorage.ts diff --git a/src/App.tsx b/src/App.tsx index 24f90b8..be860e4 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -7,11 +7,12 @@ import { songs } from './data/songs' import './App.css' import { useState } from "react"; import { useLocalStorage } from './hooks/useLocalStorage' +import { useSessionStorage } from './hooks/useSessionStorage' function App() { const [currentSongIndex, setCurrentSongIndex] = useState(0) - const [selectedAlbum, setSelectedAlbum] = useState('all') - const [sortBy, setSortBy] = useState('alphabetical') + const [selectedAlbum, setSelectedAlbum] = useSessionStorage('selectedAlbum', 'all') + const [sortBy, setSortBy] = useSessionStorage('sortBy', 'alphabetical') const [favorites, setFavorites] = useLocalStorage('favorites', []) const filteredSongs = songs.filter(song => selectedAlbum === 'all' || song.album === selectedAlbum) const sortedSongs = [...filteredSongs].sort((a, b) => a.title.localeCompare(b.title)) diff --git a/src/hooks/useSessionStorage.ts b/src/hooks/useSessionStorage.ts new file mode 100644 index 0000000..3c0bb17 --- /dev/null +++ b/src/hooks/useSessionStorage.ts @@ -0,0 +1,18 @@ +import { useEffect, useState } from "react"; + +export function useSessionStorage(key: string, initialValue: T) { + const [value, setValue] = useState(() => { + try { + const stored = sessionStorage.getItem(key) + return stored ? JSON.parse(stored) : initialValue + } catch { + return initialValue + } + }) + + useEffect(() => { + sessionStorage.setItem(key, JSON.stringify(value)) + }, [key, value]) + + return [value, setValue] as const +} \ No newline at end of file