Pull current track from Redux store

Fixes #40
This commit is contained in:
Lei Nelissen
2021-04-03 14:49:49 +02:00
parent 28b330ad4c
commit d422c1ff1e
6 changed files with 86 additions and 41 deletions

View File

@@ -1,42 +1,15 @@
import { useEffect, useState } from 'react';
import TrackPlayer, { usePlaybackState, Track } from 'react-native-track-player';
import { Track } from 'react-native-track-player';
import { useTypedSelector } from 'store';
const idEqual = (left: Track | undefined, right: Track | undefined) => {
return left?.id === right?.id;
};
/**
* This hook retrieves the current playing track from TrackPlayer
*/
export default function useCurrentTrack(): Track | undefined {
const state = usePlaybackState();
const [track, setTrack] = useState<Track>();
useEffect(() => {
const fetchTrack = async () => {
const currentTrackId = await TrackPlayer.getCurrentTrack();
// GUARD: Only fetch current track if there is a current track
if (!currentTrackId) {
setTrack(undefined);
}
// GUARD: Only retrieve new track if it is different from the one we
// have currently in state.
if (currentTrackId === track?.id){
return;
}
// If it is different, retrieve the track and save it
try {
const currentTrack = await TrackPlayer.getTrack(currentTrackId);
setTrack(currentTrack);
} catch {
// Due to the async nature, a track might be removed at the
// point when we try to retrieve it. If this happens, we'll just
// smother the error and wait for a new track update to
// finish.
}
};
fetchTrack();
}, [state, track, setTrack]);
const track = useTypedSelector(state => state.player.currentTrack, idEqual);
return track;
}