1

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

Ox Ox
  • 97
  • 6
  • trains is an array , you cannot acces the number property unless you map through it or select the first one – Kevin.a Jan 08 '21 at 20:55

3 Answers3

1

Change to:

render() {
    return (
        <div>
            <div>{this.state.station?.name}</div>
            <h1>{this.state.station?.trains[0]?.number}}</h1>
        </div>
    );
}
Or Assayag
  • 5,662
  • 13
  • 57
  • 93
  • I get another error while trying to get access to this.state.station.name. It shows that this values is undefined. Do you know what the problem might be? – Ox Ox Jan 08 '21 at 21:22
  • `console.log(this.state.station)` to see what you have there. – Or Assayag Jan 08 '21 at 21:24
  • I get the same values as on the screenshot, but when I try to show what is in `console.log(this.state.station.name) ` i shows undefined – Ox Ox Jan 08 '21 at 21:29
  • try change to `this.state.station[0].name` – Or Assayag Jan 08 '21 at 21:31
  • Thank you very much, this worked but I have another issue. I have something like this `this.state = {station: { id: this.props.match.params.id,city: '', name: '',trains: [{number: '', numberOfCarriages: '' } ] } }` I don't know how to get this value from this. Because it shows undefined. – Ox Ox Jan 08 '21 at 21:49
  • Can you please post another question in StackOverFlow? – Or Assayag Jan 08 '21 at 21:50
  • 1
    https://stackoverflow.com/questions/65637202/how-to-get-value-from-this-state-property-of-undefined. I posted question. Would you mind taking look at it? – Ox Ox Jan 08 '21 at 22:27
  • Just answer there :) – Or Assayag Jan 08 '21 at 22:29
1

Your trains property is an Array you can do this:

<h1>{this.state.station.trains[0].number}</h1>
1

If you use map you can keep in mind that there could be more than 1 train.

render() {
    return (
        <div>
            <div>{this.state.station.name}</div>
            {this.state.station.trains.map(train => <h1 key={train.id}>train.number<h1>)}
        </div>
    );
}
Kevin.a
  • 4,094
  • 8
  • 46
  • 82