peter flanagan
peter flanagan

Reputation: 9800

add a `new Audio` element to my redux store

I am trying to add a new Audio element to my redux store.

I have a reducer that looks like this:

export const songsReducer = (state = {}, action) => {

    switch (action.type) {
        case "PLAY_SONG":
           return {
             ...state,
             songPlaying: true,
             songDetails: action.song,
             audioPlaying: new Audio(action.song.url)
        }


        case "STOP_SONG":
            return {
              ...state,
              songPlaying: false,
              songDetails: null
            }

        default:
          return state;
    }

};

export default songsReducer;

However, when I check my redux store audioPlaying is an empty object like this {}

Can anyone advise what I am doing wrong here?

the component where I call the action is here

class Audio extends Component {

    static audio;

    playSong = (song) => {
        if(!this.props.audioPlaying){
            this.props.playSong(song);
            // I want to move the following lines out of the 
            // component as I need to control the audio from elsewhere in the app 
            // this.audio = new Audio(song.url); 
            // this.audio.play(); 
        } else {
            this.props.songsReducer.audio.pause();
            this.props.playSong(song);
            // this.audio = new Audio(song.url);
            // this.audio.play();
        }
    }

    render() {
       this.props.songs.map(song => {
         return (
           <li onClick={(song) => this.playSong(song)}>Play { song.name }</li>
         );
      });
    }
};

Upvotes: 0

Views: 163

Answers (1)

Atemu
Atemu

Reputation: 152

What is the Audio object?

Otherwise I would suggest to store the playing song directly in the property audioPlaying. I assume action.song.url is a string for the song url.

Instead of doing this:

audioPlaying: new Audio(action.song.url)

Do this:

audioPlaying: action.song.url

As I can see your redux state is not immutable, that might cause you some issues later on. I would suggest you to use a library like Immutable.js to solve that.

Upvotes: 1

Related Questions