1

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:

enter image description here

1 Answer 1

2

trains is array And you can access its members with Map or foreach

station.train.map(item=>item.id)
Sign up to request clarification or add additional context in comments.

1 Comment

Or trains.map({id}=>id)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.