Search code examples
javascriptreactjsapiresponse

Cannot read property 'number' of undefined ReacJS


I'm using ReactJS as frontend for my appliaction. I get values from API but when I try to get them I get error "Cannot read property number of undefined". Here is my code:

class ViewStationComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
            id: this.props.match.params.id,
            station: {}
        }
    }

    componentDidMount() {
        StationService.getStationById(this.state.id).then(res => {
            this.setState({ station: res.data });
            console.log(res.data);
        })
    }

    render() {
        return (
            <div>
                <div>{this.state.station.name}</div>
                <h1>{this.state.station.trains.number}}</h1>
            </div>
        );
    }
}

And here is the response, and value I try to get is number and numberOfCarriages. enter image description here


Solution

  • Change to:

    render() {
        return (
            <div>
                <div>{this.state.station?.name}</div>
                <h1>{this.state.station?.trains[0]?.number}}</h1>
            </div>
        );
    }