Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make requests in react correctly?

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.

Here's the code I have

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 =)

like image 221
Max Popov Avatar asked Mar 05 '23 09:03

Max Popov


2 Answers

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;

like image 99
Shubham Gupta Avatar answered Mar 15 '23 04:03

Shubham Gupta


Just Syntax:

<button onClick={() => this.getWeather(city)}>touch me soy boy</button>
like image 40
Vlad Avatar answered Mar 15 '23 06:03

Vlad