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:
class ListStation extends Component { constructor(props) { super(props) this.state = { stations: [] } this.addStation = this.addStation.bind(this); this.editStation = this.editStation.bind(this); this.deleteStation = this.deleteStation.bind(this); this.showTrains = this.showTrains.bind(this); } deleteStation(id) { StationService.deleteStation(id).then(res => { this.setState({ stations: this.state.stations.filter(station => station.id !== id) }); }) } editStation(id) { this.props.history.push(`/add-station/${id}`); } componentDidMount() { StationService.getStations().then((res) => { this.setState({ stations: res.data }); }) } addStation() { this.props.history.push('/add-station/_add'); } showTrains() { this.props.history.push('/show-train'); } render() { return ( <div> <div className="row"> <table className="table table-striped table-bordered"> <tbody> {this.state.stations.map( station => <tr key={station.id}> <td>{station.city}</td> <td>{station.name}</td> <td>{station.trains.id}</td> {/* {console.log(station.trains.id)} */} {console.log(station.name)} )} </tbody> </table> </div> </div> ); } }
And here is the response I get from API:
Advertisement
Answer
trains is array And you can access its members with Map
or foreach
station.train.map(item=>item.id)