Skip to content
Advertisement

Succeeded in fetching data, but it gives TypeError: Cannot read property ‘0’ of null

I have another problem today.

ComponentDidMount seems to work fine(it brings data from the server), but when I try to use the data I received, it’d throw TypeError: Cannot read property ‘0’ of null.

What I’m trying to do is to play one of the videos I received from fetching data from the server. I receive my data as an array of nested objects, which is the reason to using [0] to get a certain index of the array elements, but it’d give an error.

Here is part of my function,

class Favorites extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            favVideos: null,
        };
    }

    componentDidMount() {
        axios.get("https://test/favorites",
            { withCredentials: true })
            .then((res) => {
                console.log("fav componentdidmount data.userFav[0]>>", res.data.userFavorites[0])
                this.setState({
                    favVideos: res.data.userFavorites
                })
            })
    }

    render() {
        return (
            <div id="fav-list-container">
                <div id="fav-list-body">
                    <div id="fav-list-title">Favorites</div>
                    <span id="favorites-select-all"></span>
                </div>
                <div>
                    <li>videotest
                        <div className="fav-video-thumbnail">
                            <iframe
                                src={`${this.state.favVideos[0].contentlink}`}
                                frameBorder="0"
                                allow="autoplay; encrypted-media"
                                title={`${this.state.favVideos[0].contentname}`}
                            />
                        </div>
                        <div>
                            <span>{this.state.favVideos[0].contentname}</span>
                        </div>
                    </li>
          
                </div>
            </div>
        )
    }
}

I have also tried my iframe as below

<iframe
  src={this.state.favVideos[0].contentlink}
  frameBorder="0"
  allow="autoplay; encrypted-media"
  title={this.state.favVideos[0].contentname}
/>

I am sorry if my question was confusing, please let me know if there’s any confusion I should clarify. Thank you inadvance.

Advertisement

Answer

Fetching data from the backend server is async. thats why you need to handle first rendering part as well as null and undefined data set from the backend. for this you can add check for null and undefined values in array.

((this.state.favVideos && this.state.favVideos[0]) || {}).contentLink

add this in render

8 People found this is helpful
Advertisement