0

This is my code

My state

this.state = {
    loading: true,
    weather: [],
    cityName: [],
    selectedOption: '',

}

My call api

const getAPIcityName = Axios.get('http://dataservice.accuweather.com/locations/v1/topcities/100?').then((res) => {
        console.log('res' + res);
        this.setState({ cityName: res.AdministrativeArea.LocalizedName });
    }, (error) => {
        console.log('error', error)
    });
}

And here i wont to do the Select the name of the city

handleChange(selectedOption) {
    this.setState({ selectedOption });
    console.log(selectedOption);
}

render() {
    let options = this.state.cityName.map((cityName) => {
        return cityName.AdministrativeArea.LocalizedName;
    })

    return (
        <div class="container">

            <h1 for="Search">Search</h1>
            <form>

                <Select
                    name="form-field-name"
                    value={this.state.value}
                    onChange={this.handleChange}
                    options={options}
                />

And here it works

{/* <select class="custom-select custom-select-lg mb-3">
    {this.state.cityName.map(cityName => <option key={cityName.Key}>{cityName.AdministrativeArea.LocalizedName}</option>)}
</select> */}

And this is the Error

Unhandled Rejection (TypeError): Cannot read property 'LocalizedName' of undefined

3
  • cityName.AdministrativeArea is undefined, that's why you are getting that error. you need to initialize it in your constructor or await your API call. Commented Sep 25, 2019 at 22:02
  • What is the structure of the cityName array? Commented Sep 25, 2019 at 22:03
  • Hi Itzik, check my solution and let me know if that helps. Commented Sep 26, 2019 at 2:40

1 Answer 1

1

If my understanding is correct, you are using react-select.

react-select needs options array in the following format,

const options = [
  { value: '', label: '' },
  { value: '', label: '' },
  ...
]

Your options should be in above format.

As your data is coming from an API, you need to first check if you have data in state and then only iterate over the state to get options

let options = [];

if(this.state.cityName && this.state.cityName.length > 0){
   options = this.state.cityName.map((cityName) => {
        return {value: cityName.AdministrativeArea.LocalizedName, label: cityName.AdministrativeArea.LocalizedName};
    })
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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