I am new to ReactJS and I'm trying to create field where I can write down a city name and get it's current weather.
const key = '&APPID=fe338dab6a1fd5b27b01a15c12a16391'
const URL = 'http://api.openweathermap.org/data/2.5/weather?q=';
class Index extends React.Component {
constructor(prop) {
super(prop);
this.state = {
city: '',
data: [],
isLoaded: false
}
}
getWeather(city) {
fetch(URL + city + key)
.then(response => response.json())
.then(data => console.log(data));
}
updateCity(e) {
this.setState({city: e.target.value});
}
render() {
let city = this.state.city;
return (
<div>
<input type="text" name="city" onChange={this.updateCity.bind(this)} />
<button onClick={this.getWeather(city)}>touch me soy boy</button>
</div>
);
}
}
export default Index;`
My problem is that it sends requests every time I write a symbol. How to make it send request only when I press the button?
Also, recommend me any sources where I can learn more about React to stop asking questions on this site =)
Why do you want to pass city when you are maintaining it in state.
<button onClick={this.getWeather}>Get Weather</button>
And in your getWeather function get the city const {city} = this.state;
Just Syntax:
<button onClick={() => this.getWeather(city)}>touch me soy boy</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With