React event target value from jsx element does not get bind to state and json array (Type error cannot read the properties of undefined )
You should check if the data have been loaded before displaying them.
Adding a check in the render
method should prevent the error:
render() {
if (!this.state.locations || !this.state.restaurants) {
return <>Loading data...</>;
}
let locationList =
this.state.locations.length &&
this.state.locations.map((item) => (
<option key={item.name} value={item.city_id}>
{item.name}
</option>
));
let restaurantList = this.state.restaurants.length && (
<ul>
{this.state.restaurants.map((item) => (
<li key={item.name}>{item.name}</li>
))}
</ul>
);
...
}
Also, try to change your setState
calls like this:
fetch('http://localhost:5252/zomato/locations', { method: 'GET' })
.then((response) => response.json())
.then((data) =>
this.setState({
...this.state,
locations: data.data,
})
);
...
fetch(`http://localhost:5252/zomato/restaurants/${event.target.value}`, {
method: 'GET',
})
.then((response) => response.json())
.then((data) => {
this.setState({ ...this.state, restaurants: data.data });
});