简体   繁体   中英

How can I change this axios API request into a fetch() function for a React app?

This is the code I have for the axios call for API, I have to migrate it to a fetch() function:

  handleClick = e => {
    axios
      .post(
        "https://api.openweathermap.org/data/2.5/weather?q=" +
          this.state.term +
          "&units=metric&appid=" +
          API_KEY
      )
      .then(res => {
        this.setState({
          city_name: res.data.name,
          temp: res.data.main.temp,
          humidty: res.data.main.humidity,
          wind: res.data.wind.speed,
          weather_status: res.data.weather[0].main,
          weather_desc: res.data.weather[0].description,
          weather_icon: res.data.weather[0].icon
        });
      })//error logging
      .catch(error => {
        console.log(error);
      });
  };

  render() {
    return (
      <div className="container">
        <h1 className="header">Task 14 - Level 2</h1>
        <Form onChange={this.handleChange} onClick={this.handleClick} />
        <WeatherApp data={this.state} />
        <div className="img"></div>
      </div>
    );
  }
}

How would I change the axios call to a fetch() function?

This is the equivalent in fetch.

const handleClick = () => {

   fetch( "https://api.openweathermap.org/data/2.5/weather?q=" +
          this.state.term +
          "&units=metric&appid=" +
          API_KEY,{ method: 'POST' }). then( res => res.json())
          .then( res => {
   this.setState({
          city_name: res.data.name,
          temp: res.data.main.temp,
          humidty: res.data.main.humidity,
          wind: res.data.wind.speed,
          weather_status: res.data.weather[0].main,
          weather_desc: res.data.weather[0].description,
          weather_icon: res.data.weather[0].icon
        });

})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM