SkyeBoniwell
SkyeBoniwell

Reputation: 7112

Cannot read property 'length' of null when checking array

I'm trying to show some photos on a website. Everytime I try, I get this error:

Cannot read property 'length' of null

import React, { Component } from 'react';
import axios from 'axios';


class ImagePlayer extends Component {
constructor(props) {
    super(props);
    this.state = {
        photos: null
    };
}

componentDidMount() {
    axios.get(`/api/gameDev/image-files/${this.props.charId}/pics`)
        .then((response) => {
            this.setState({ photos: response.data })
        })
        .catch((error) => {
            console.log(error);
        });

}

showMedia = (props) => {
    return (
        <div>
            {
                props.photos.length > 0 &&
                    <div>
                        {props.photos.map((photo) => photo.title)}
                    </div>
            }
        </div>
    );
}

render() {
    return (
        <div>
            <div>Show Media</div>
            <div>
                {this.showMedia(this.state)}
            </div>
        </div>
    );
}

}

export default ImagePlayer;

I know I did something wrong. If anyone can see anything, please let me know.

Thanks! :)

Upvotes: 0

Views: 2111

Answers (2)

Rodius
Rodius

Reputation: 2311

The first time the render is mounted the state has photos as a null. You need to set it to an initial empty array so this stage won't fail:

this.state = {
  photos: []
};

Upvotes: 1

Roy Wang
Roy Wang

Reputation: 11270

Set initial photos state to an empty array:

this.state = {
    photos: []
};

Alternatively, change props.photos.length > 0 to:

props.photos && props.photos.length > 0 // or (props.photos || []).length > 0

Upvotes: 4

Related Questions