Skip to content

Commit

Permalink
fix: fixed audio stop on route change
Browse files Browse the repository at this point in the history
  • Loading branch information
sirLisko committed Sep 17, 2024
1 parent f6f19d6 commit 37792c8
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions components/Tracks/Tracks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import classNames from "classnames";
import SpotifyLogo from "components/Icons/Spotify";
import PauseIcon from "components/Icons/Pause";
import PlayIcon from "components/Icons/Play";
import { useRouter } from "next/router";

interface TracksProps {
tracks: Track[];
Expand All @@ -19,6 +20,7 @@ const Tracks = ({ tracks, links, palette }: TracksProps) => {
const [loaded, setLoaded] = useState(false);
const [currentTrack, setCurrentTrack] = useState<string | null>(null);
const [audio, setAudio] = useState<HTMLAudioElement | null>(null);
const router = useRouter();

const handlePreview = (audioUrl: string | undefined, title: string) => {
if (!audioUrl) return;
Expand All @@ -36,6 +38,26 @@ const Tracks = ({ tracks, links, palette }: TracksProps) => {
}
};

useEffect(() => {
const handleRouteChange = () => {
if (audio) {
audio.pause();
setAudio(null);
setCurrentTrack(null);
}
};

router.events.on("routeChangeStart", handleRouteChange);

return () => {
if (audio) {
audio.pause();
setAudio(null);
}
router.events.off("routeChangeStart", handleRouteChange);
};
}, [audio, router.events]);

useEffect(() => {
setTimeout(() => setLoaded(true), 1);
}, []);
Expand Down

0 comments on commit 37792c8

Please sign in to comment.