简体   繁体   中英

React app crashes if the API-URL is not valid

I'm trying to write my very first React application. In a form with two input fields, the user type the name of a country and a city inside the input fields and submit the form. city and country variables are then passed to the following component, which should send an API-Request to openweatehrmap API and show the results.

import React, { Component } from 'react';
import axios from 'axios';
import Form from './Form/Form';

class Weather extends Component {
  state = {
    country: '',
    city: '',
    currentTemp: '',
    error: undefined,
  }


  getWeather = async (e) => {
    e.preventDefault();
    const URL = 'http://api.openweathermap.org/data/2.5/weather?q='
    const API_KEY = "8b46d478a9...34a69";
    const country = e.target.elements.country.value;
    const city = e.target.elements.city.value;
    try {
      if (country && city) {
        const response = await 
axios.get(`${URL}${city},${country}&appid=${API_KEY}&units=metric`);
        const data = await response;
        console.log(data);
        this.setState({
          country: data.data.sys.country,
          city: data.data.name,
          currentTemp: data.data.main.temp,
          error: '',
        });
      } else {
        this.setState({
          country: undefined,
          city: undefined,
          currentTemp: undefined,
          error: 'Please enter a country and a city name'
        })
      }
    } catch (err) {
      this.setState({ error: err })
    }
  }


  render() {
    let showResult;
    if (this.state.error !== undefined && this.state.country && this.state.city) {
      showResult =
        <ul>
          <li>Location: {this.state.country} {this.state.city}</li>
          <li>Current Temperature: {this.state.currentTemp}° Celsius</li>
        </ul>
    }
    else {
      showResult = <div className="error">
        {this.state.error}
      </div>
    }

    return (
      <div>
        <Form onGetWeather={this.getWeather} />
        {showResult}
      </div>
    );
  }
}

export default Weather;

If you let one or both input fields empty and submit the form, the UI shows an error. If you fill in both input fields and the country and the city are related (for example UK and London), the UI shows the temperature and some other info.

However , If you fill in both input fields with just some random text, or if the country and the city are not related to each other, the App crashes as soon as the form is submitted.

I think this is because that the generated API-URL isn't valid any more. The console shows the following error:

在此处输入图片说明

I spent a whole day, but I couldn't find a way to fix it. How can I avoid the app from crashing. How can I validate the generated API-URL? Or any other hint or solution?

Thanks guys.

I think I managed to fix it after reading your comments. I had to change the catch part to this:

catch (err) {
      if (err.response) {
        console.log(err.response.data);
        this.setState({ error: err.response.data.message });
      }
    };

What do you think?

Is there anything else in my code, that could be improved? (I'm sure there are many)

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