Last active
February 25, 2022 16:16
-
-
Save Yidaotus/3a17bc2b863a857be1b5f9356b004563 to your computer and use it in GitHub Desktop.
Currently Playing Custom Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type PollingMode = "STATIC" | "CALCULATED"; | |
const BUFFER_TIME = 5000; | |
const WAIT_ON_ERROR = 60000; | |
const POLLING_RATE = 10000; | |
const POLLING_MODE: PollingMode = "CALCULATED"; | |
const useCurrentlyPlaying = () => { | |
const [playingItem, setPlayingItem] = useState<SpotifyPlayer>(); | |
const [fetching, setFetching] = useState(false); | |
useEffect(() => { | |
let timeoutId: number; | |
const fetchPlayingState = async () => { | |
let refreshTimeInMs = WAIT_ON_ERROR; | |
setFetching(true); | |
try { | |
const fetchResult = await fetchSpotifyPlayer(); | |
if ( | |
fetchResult.CurrentlyPlayingData && | |
!fetchResult.CurrentlyPlayingErrors | |
) { | |
const { player } = | |
fetchResult.CurrentlyPlayingData.me.spotify; | |
setPlayingItem(player); | |
if (POLLING_MODE === "STATIC") { | |
refreshTimeInMs = POLLING_RATE; | |
} else { | |
refreshTimeInMs = | |
player.item.durationMs - | |
player.progressMs + | |
BUFFER_TIME; | |
} | |
} | |
} catch (e) { | |
// Gimmick | |
} | |
setFetching(false); | |
timeoutId = window.setTimeout(fetchPlayingState, refreshTimeInMs); | |
}; | |
fetchPlayingState(); | |
return () => { | |
if (timeoutId) { | |
clearTimeout(timeoutId); | |
} | |
}; | |
}, [setPlayingItem, setFetching]); | |
return [playingItem, fetching] as const; | |
}; | |
export default useCurrentlyPlaying; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment