Skip to content

Instantly share code, notes, and snippets.

@Yidaotus
Last active February 25, 2022 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yidaotus/3a17bc2b863a857be1b5f9356b004563 to your computer and use it in GitHub Desktop.
Save Yidaotus/3a17bc2b863a857be1b5f9356b004563 to your computer and use it in GitHub Desktop.
Currently Playing Custom Hook
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