Dawn17
Dawn17

Reputation: 8297

Adding an Audio object to my react state array

componentWillMount() {

    console.log('Component WILL MOUNT!')

    axios.get('/channels').then( (res) => {
        console.log(res.data.data.playList);
        this.setState({
            categories: res.data.data.playList,
            audioList: res.data.data.playList.url
        })
    }).catch( (err) => {
        console.log(err);
    });


}   

In my componentWillMount() I get bunch of mp3 urls from a database and stores into a state called audioList so it has a bunch of URLs of a sound file. However, what I actually want to store is an Audio object (HTML5 Audio).

Usually, to make it playable, I would have to make a new Audio object like

this.audio = new Audio([URL]);

then do

this.audio.play()

Since I want to make a list of music, I would like to but everything like

this.state.audioList = [ audioObject1, audioObject2, audioObject3, ... ]

How can I do this?

EDIT

componentWillMount() {

    console.log('Component WILL MOUNT!')

    let playLists = [];

    axios.get('/channels').then( (res) => {
        //console.log(res.data.data.playList);
        res.data.data.playList.map((value, key) => playLists.push(new Audio(value.url)));
        this.setState((prevState) => {
            return { audioList: playLists}
        }, () => console.log("dddd" + this.state.audioList));

    }).catch( (err) => {
        console.log(err);
    });

}  

This gives me

enter image description here

EDIT2

componentWillMount() {

    console.log('Component WILL MOUNT!')


let playLists = [];

axios.get('/channels').then( (res) => {
    //console.log(res.data.data.playList);
    res.data.data.playList.map((value, key) => playLists.push(new Audio(value.url)));
    this.setState((prevState) => {
        return { audioList: playLists, categories: res.data.data.playList}
    });
}).catch( (err) => {
    console.log(err);
});

}   

enter image description here

Upvotes: 0

Views: 394

Answers (1)

Elumalai Kaliyaperumal
Elumalai Kaliyaperumal

Reputation: 1520

You can try with array push like below for objects available inside array,

let playlists = [];
res.data.data.playList.map((value, key) => playlists.push(new Audio(value.url)));
this.setState((prevState) => {
    return { audioList: playlists}
}, () => console.log(this.state.audioList));

Upvotes: 2

Related Questions