Skip to content
Advertisement

How to autoplay the next song onClick on a btn

I am in front of a problem. I am trying to create a music player. But now, I have a problem with my loading of the next music at the click of the next button. The new data is replaced in the state and in the render, but the music does not play by itself after the button is clicked. I think I should used the load () function of an audio or video element to reload the media but it doesn’t work. I put my code for you so you can look. It is certainly not perfect, I am aware that I could improve some point of my code.

What i’m trying to do is when the next function is launch. I take the current song then add +1 for the new information then i update the state with the new information. When the new informations are in the state i pause the music then load the new song and after i launch the playing function who check if he need to pause or play the music. If anyone could give me a lead on how to solve the problem it would be great !

Thx a lot !

JavaScript

Advertisement

Answer

You are working with stale state when you enqueue the state update and then try to call pause, load the audio, and play. The component hasn’t rerendered for the this.audio ref to have updated yet either.

After the state update is enqueued you will want to pause the currently playing track and use the componentDidUpdate lifecycle hook to start the next.

JavaScript

You will need to apply a similar fix to prev. In fact, since these two functions are basically the same, the only difference is incrementing/decrementing the current/next value, you can combine these into a curried function and close over in scope the incrementing/decrementing value.

JavaScript

The title, image, and song source all considered “derived” state, meaning that from the actual currentMusic state and the data you can derive this “state”.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement