I’m trying to get values from trains such as id and number, but when I try to do that, no values shows. When I try to console.log that I get response of undefined. It works well with station.name and station.city but i does not work with station.trains.is. Here is my code:
JavaScript
x
65
65
1
class ListStation extends Component {
2
constructor(props) {
3
super(props)
4
5
this.state = {
6
stations: []
7
}
8
9
this.addStation = this.addStation.bind(this);
10
this.editStation = this.editStation.bind(this);
11
this.deleteStation = this.deleteStation.bind(this);
12
this.showTrains = this.showTrains.bind(this);
13
}
14
15
deleteStation(id) {
16
StationService.deleteStation(id).then(res => {
17
this.setState({ stations: this.state.stations.filter(station => station.id !== id) });
18
})
19
}
20
21
editStation(id) {
22
this.props.history.push(`/add-station/${id}`);
23
}
24
25
componentDidMount() {
26
StationService.getStations().then((res) => {
27
this.setState({ stations: res.data });
28
})
29
}
30
31
addStation() {
32
this.props.history.push('/add-station/_add');
33
}
34
35
showTrains() {
36
this.props.history.push('/show-train');
37
}
38
39
render() {
40
return (
41
<div>
42
<div className="row">
43
<table className="table table-striped table-bordered">
44
45
<tbody>
46
{this.state.stations.map(
47
station =>
48
<tr key={station.id}>
49
<td>{station.city}</td>
50
<td>{station.name}</td>
51
<td>{station.trains.id}</td>
52
{/* {console.log(station.trains.id)} */}
53
{console.log(station.name)}
54
55
)}
56
57
</tbody>
58
</table>
59
</div>
60
</div>
61
);
62
}
63
}
64
65
And here is the response I get from API:
Advertisement
Answer
trains is array And you can access its members with Map
or foreach
JavaScript
1
2
1
station.train.map(item=>item.id)
2