After following one of tutorials and playing with the code, I got my weather app working. I also get a nice error message if I don’t enter any value and press the button, but if I enter “wrong” value (city is not in API’s database), the app crashes. Is there any chance I could have something like live input search field? For example, if I start typing ''MA…" only cities with those two first letters will appear and I can click on any of them? We have all seen such search fields, but I have no idea if it is possible to be done by someone who is learning like myself or you need some advanced knowledge.
Here is the code:
class App extends React.Component {
state = {
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
pressure: undefined,
description: undefined,
error: undefined
}
getWeather = async (e) => {
e.preventDefault();
const city = e.target.elements.city.value;
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=${API_KEY}&units=metric`);
const data = await api_call.json();
if (city) {
this.setState({
temperature: data.main.temp,
city: data.name,
country: data.sys.country,
humidity: data.main.humidity,
pressure: data.main.pressure,
description: data.weather[0].description,
error: ""
});
} else {
this.setState({
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
pressure: undefined,
description: undefined,
error: "Please enter city name..."
});
}
}
render() {
return (
<div>
<div className="wrapper">
<div className="main">
<div className="container">
<div className="row">
<div className="col col-xs-6 col-sm-6 col-md-6 col-lg-6 col-xl-6 title-container">
<Titles />
</div>
<div className="col col-xs-6 col-sm-6 col-md-6 col-lg-6 col-xl-6 form-container">
<Form getWeather={this.getWeather}/>
<Weather
temperature={this.state.temperature}
city={this.state.city}
country={this.state.country}
humidity={this.state.humidity}
pressure={this.state.pressure}
description={this.state.description}
error={this.state.error}
/>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
};
export default App;
also, another problem is that there are some cities with the same name, so I would really need that live search option. If that is too difficult, how could I just stop my app from crashing if city is not in API’s database?