2 years ago

#58216

test-img

huzzzus

React Audio src is not updating on state change

I have a list of tracks with a play button on each track which if clicked sets(setCurrentSong hook) the current song(title, src, artist) to be the song that was clicked on and toggles the isPlaying (true, false).

useEffect fires on [isPlaying], but the audio source does not update and it fails to play.

Audio tag

<audio ref={audioElem} src={currentSong.file}></audio>

Hooks and use effect.

const [songs, setSongs] = useState(songsdata);
const [currentSong, setcurrentSong] = useState({});
const [isplaying, setisPlaying] = useState(false)
const audioElem = useRef(null)

useEffect(() => {
    setcurrentSong(songs[0])
}, [])

useEffect(() => {
    if (isplaying) {
        audioElem.current.load()
        audioElem.current.play();
    }
    else {
        audioElem.current.pause();
    }
}, [isplaying])

reactjs

audio

use-ref

0 Answers

Your Answer

Accepted video resources