I have been trying to update my videos so that only one will be playing at a time whenever another video is clicked my state seems to be undefined after clicking the play button and i am not too sure why or if this is the best way to go about what i am trying to achieve can anyone help me out?
This is my main component:
const [allVideos, setAllVideos] = useState(initVideos(data));
function generateVideo(data, index) {
return {
url: data[index].url,
id: data[index].id,
playing: false,
};
}
function initVideos(data) {
const videos = [];
for (let i = 0; i < data.length; i++) {
videos.push(generateVideo(data, i));
}
return videos;
}
const videos = allVideos.map((item) => {
return (
<>
<Playlist url={item.url} id={item.id} playing={item.playing} />
<button onClick={() => playVideo(item.id)}>Play</button>
</>
);
});
function playVideo(id) {
setAllVideos((oldVideos) => {
oldVideos.map((video) => {
return video.id === id
? { ...video, playing: !video.playing }
: { ...video, playing: false };
});
});
}
return (
<div className="sidebar-container" style={styles.container}>
<button className="add-playlist" onClick={(props) => addPlaylist()}>
Add New Playlist
</button>
<p>sidebar for now!</p>
{videos}
</div>
);
}
here is my playlist component which the array is made up of:
return (
<div className="playlist-container">
<Container>
<ReactPlayer url={props.url} id={props.id} playing={props.playing} />
</Container>
<p>This is the playlists name {props.name}</p>
<p>The playlist is {props.playtime} long</p>
</div>
);
}
can anyone suggest how to solve my issue or a better way about making sure only a single video can play at a time?