Search code examples
reactjssetstate

Perform setState after audio is played completely


Basically I have a recorded audio in the UI which has a play/pause button. there is a state property playing which decides what icon should be rendered in that button depending on whether this.state.playing is true or false. Now the problem is after the audio is played completely, the pause icon does not get changed to play icon automatically, reason being this.state.playing still remains true. I understand that I need to perform a setState and change playing to false after the audio play is completed. My question is where should I need to perform the setState to ensure it gets executed only after the audio is played completely?

state = {
        playing: false
    }

onPlayPause = () => {
        let { playing } = this.state 
        if(playing) {
            this.setState({ playing: false })
            this.audio_el.current.pause()
        } else {
            this.setState({ playing: true })
            this.audio_el.current.play()
            // Need to make {playing: false} only after play() is completed
        }
    }

Inside render() method:

<Button onClick={ this.onPlayPause } icon={ playing ? "pause" : "play" }/>

I tried performing setState inside componentDidMount() but no luck :(


Solution

  • Try bind new method with setState only via media event (more about it here: https://reactjs.org/docs/events.html#media-events) called onEnded on audio element. That should do the work.

    You have something like this in render():

    <audio src="..." onEnded={this.setFinished}>
    

    And then add this method:

    setFinished = () => {
        this.setState({
            playing: false
        })
    }