javascript – Removing video element not working with Reactjs


I’m creating a WebRTC app where I need to show the new users video feed when its connected and removing when they’ve left.

import React, { Component } from 'react';
import Peer from 'peerjs';


class Host extends Component {
    constructor(props) {
        super(props);
        this.peer = new Peer();
        this.state = { streams: () };
    }

    async componentDidMount() {
        const self = this;

        this.peer.on('open', function(id) {
            self.peer.on('call', (call) => {
                console.log('Incoming call...');
                call.answer(stream);
                call.on('stream', (remoteStream) => {
                    let streams = (...self.state.streams, {src: remoteStream, connId: call.connectionId, display: true});
                    self.setState({ streams });
                    console.log('Call received...');
                })

                call.on('iceStateChanged', (state) => {
                    if (state == 'disconnected') {
                        self.setState(prevState => ({
                        streams: prevState.streams.map(
                            s => s.connId === call.connectionId ? { ...s, display: false }: s
                        )}))
                        console.log('Call disconnected');
                    }
                })
            })
        }
    }
    
    render() {
        return(
            <>
            {this.state.streams.map((stream, idx) => {
                if (!stream.display)
                    return null

                return <video autoPlay key={idx} ref={(ref) => {ref.srcObject = stream.src}}></video>
            })}
            <>
        );
    }
}

export default Host;

I’m able to dynamically create the video element but removing is where I’m facing problems.
Whenever iceStateChanged event is called i.e. when user disconnects it throws the following error.

Uncaught TypeError: Cannot set property 'srcObject' of null