2

I'm trying to get values and insert them in the dropdown. But when I try to do that I get value as undefined instead of proper value. I want to get values from train array and populate dropdown with them. When I get station.name correct value is returned, but when i try to access train.number undefined value is returned.

import React, { Component } from 'react';
import StationService from '../services/StationService';

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

        this.state = {
            station: {
                id: this.props.match.params.id,
                city: '',
                name: '',
                trains: [
                    {
                        number: '',
                        numberOfCarriages: ''
                    }
                ]
            }
        }

        this.changeCityHandles = this.changeCityHandles.bind(this);
        this.changeNameHandles = this.changeNameHandles.bind(this);
        this.saveStation = this.saveStation.bind(this);
    }

    componentDidMount() {

        if (this.state.station.id === '_add') {
            return;
        } else {
            StationService.getStationById(this.state.station.id).then((res) => {
                let station = res.data;
                this.setState({ name: station.name, city: station.city, number: station.trains.number })
            });
        }
        // console.log(this.state.station.name + 'dfddddd');
    }

    changeCityHandles = (event) => {
        this.setState({ number: this.state.station, trains: event.target.value });
    }

    changeNameHandles = (event) => {
        this.setState({ name: event.target.value });
    }

    saveStation = (e) => {
        e.preventDefault();
        let station = { city: this.state.city, name: this.state.name, number: this.state.train.number, numberOfCarriages: this.state.train.numberOfCarriages }

        if (this.state.station.id === '_add') {
            StationService.createStation(station).then(res => {
                this.props.history.push('/stations');
            });
        } else {
            StationService.updateStation(station, this.state.station.id).then(res => {
                this.props.history.push('/stations');
            });
        }
    }

    cancel() {
        this.props.history.push('/stations');
    }

    getTitle() {
        if (this.state.id === '_add') {
            return <h3 className="text-center">Dodaj stację</h3>
        } else {
            return <h3 className="text-center">Modyfikuj stację</h3>
        }
    }

    render() {
        return (
            <div>
                <div className="container">
                    <div className="row">
                        <div className="card-body">
                            <form>

                                <div className="form-group">
                                    <input  name="name" className="form-control" value={this.state.name} onChange={this.changeNameHandles} />
                                </div>

                                    <select>
                                        {this.state.station.trains.map(train => <option key={train.id} value={train.number}>{train.number}</option>)}

                                    </select>
  
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
8
  • What's the bug line? Commented Jan 9, 2021 at 21:02
  • This value is undefined {this.state.station.trains.map(train => <option key={train.id} value={train.number}>{train.number}</option>)} Commented Jan 9, 2021 at 21:35
  • Do you get any value when you try to console.log(this.state.station.trains) Commented Jan 9, 2021 at 22:15
  • @SinanYaman I get [object Object] Commented Jan 9, 2021 at 22:30
  • Can you try this for debugging purposes: <select> {this.state.station.trains.map(train => { console.log(train); return <option key={train.id} value={train.number}>{train.number}</option> })} </select> and see if you get any data when you try to log the train object Commented Jan 10, 2021 at 7:36

3 Answers 3

1
    Try this:-
    
        {this.state.station && this.state.station.trains.length && 
 && this.state.station.trains.map((train , i) => {
                return (
                     <React.Fragment>
                            { train && train?.number &&
          <option key={train?.id} value={train?.number}>{train?.number}</option>       
                             }
                     </React.Fragment>
                          );
         })
    }
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for answer, but it still doesn't work.
Updated answer.
There is still no difference. Values are empty
This can only happen when train.number have some whitespace. Use trim() for that.
There are not any whitespaces. I guess the problem is somewhere else but I don't know where exactly
1

It's trains[0].number not trains.number, because the object you are trying to access is nested in an array.

Comments

1
StationService.getStationById(this.state.station.id).then((res) => {
                let station = res.data;
                this.setState({ name: station.name, city: station.city, number: station.trains.number })
            });

This code tries to set state variables of name, city and number. Instead try doing this

            StationService.getStationById(this.state.station.id).then((res) => {
                let station = res.data;
                this.setState({ station: { 
                     ...state.station,
                     name: station.name,
                     city: station.city,
                     trains: station.trains }
                 })
               });

2 Comments

You could do this.setState({station)} directly but I am assuming you don't want to overwrite the id
You have the same issue everywhere you setState. Please do some work before asking another question, as you know the problem and the solution now. Try on your own and ask another question if there is another issue. Cheers

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.