Skip to content

Commit

Permalink
Save Playlist Selection in Local Storage (#93)
Browse files Browse the repository at this point in the history
  • Loading branch information
ras1 authored Sep 21, 2023
2 parents 3b2cccf + d498d67 commit dbf6aaa
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions src/pages/ShufflePlayer.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,43 @@ function ShufflePlayer() {
const [playlists, setPlaylists] = useState([])
const [currentVideo, setCurrentVideo] = useState({})
const [playedVideos, setPlayedVideos] = useState([])
const [selectedPlaylistIds, setSelectedPlaylistIds] = useState([])
const [selectedPlaylistIds, setSelectedPlaylistIds] = useState(() => {
const saved = localStorage.getItem("selectedPlaylistIds");
const initialValue = JSON.parse(saved);
return initialValue || [];
})
const [repeatVideo, setRepeatVideo] = useState(false)
const [hideVideo, setHideVideo] = useState(true)
const [hideDescription, setHideDescription] = useState(true)

const [videosResult, fetchPlaylistVideos] = useVideoHook(selectedPlaylistIds)
useEffect(loadPlaylists, [])
useEffect(pickNextVideo, [videosResult])
useEffect(() => {
localStorage.setItem("selectedPlaylistIds", JSON.stringify(selectedPlaylistIds));
}, [selectedPlaylistIds]);

useCallbackOnce(loadPlaylists)

function useCallbackOnce(callbackFunction, condition = true) {
const isCalledRef = React.useRef(false);

React.useEffect(() => {
if (condition && !isCalledRef.current) {
isCalledRef.current = true;
callbackFunction();
}
}, [callbackFunction, condition]);
}

function loadPlaylists() {
axios.get(AppConstants.APIEndpoints.TRACKED_PLAYLISTS)
.then(response => setPlaylists(response.data))
.then(response => {
response.data = response.data.map(item => ({
...item,
is_default: selectedPlaylistIds.length > 0 ? selectedPlaylistIds.includes(item.playlist_id) : item.is_default
}))
setPlaylists(response.data)
})
.catch(error => console.log(`Couldn't retrieve tracked playlists! ${error}`))
}

Expand Down

0 comments on commit dbf6aaa

Please sign in to comment.